using UnityEngine;
using System;
using System.Collections.Generic;

namespace mgaia.Utils
{
    public abstract class AbstractReusablePool
    {
        private List<IReusable> mPool = new List<IReusable>();
        private AbstractReusableFactory mFactory;

        protected abstract bool IsMatch(IReusable reusable, object filter);

        protected AbstractReusablePool(AbstractReusableFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            this.mFactory = factory;
        }

        public IReusable Find(Predicate<IReusable> predicate)
        {
            return mPool.Find(predicate);
        }

        public IReusable Acquire(object filter)
        {
            foreach (IReusable reusable in mPool)
            {
                if (reusable.Available)
                {
                    if (IsMatch(reusable, filter))
                    {
                        return reusable;
                    }
                }
            }

            IReusable created = mFactory.Create(filter);
            created.Destroyed += delegate(object sender, EventArgs e)
            {
                IReusable r = (IReusable)sender;
                mPool.Remove(r);
            };
            mPool.Add(created);

            return created;
        }
    }
}