using System;
using System.Collections.Generic;

namespace Idleventures.Pooling
{
    [Serializable]
    public class ObjectPool
    {
        public PooledObject PooledObject { get; set; }

        public List<PooledObject> PooledObjects = new List<PooledObject>();

        public PooledObject GetObject()
        {
            PooledObject toReturn;

            if (PooledObjects.Count <= 0)
                CreateObject();
            
            toReturn = PooledObjects[0];
            PooledObjects.RemoveAt(0);

            return toReturn;
        }

        public void CreateObject()
        {
            PooledObject obj = UnityEngine.GameObject.Instantiate<PooledObject>(PooledObject);
            obj.Pool = this;
            
            AddObjectToPool(obj);
        }

        public void AddObjectToPool(PooledObject pooledObject)
        {
            if (!PooledObjects.Contains(pooledObject))
            {
                PooledObjects.Add(pooledObject);
                pooledObject.gameObject.SetActive(false);
            }
        }

        public void PreCreateObjects(int amount)
        {
            for (int i = 0; i < amount; i++)
            {
                CreateObject();
            }
        }
    }
}