using System.Collections.Generic;
using UnityEngine;

namespace Idleventures.Pooling
{
    public class ObjectPoolController : MonoBehaviour
    {
        #region Singleton

        private static ObjectPoolController _instance;
        public static ObjectPoolController Instance
        {
            get
            {
                if (_instance == null)
                    _instance = GameObject.FindObjectOfType<ObjectPoolController>();
                return _instance;                
            }
        }

        #endregion

        public List<ObjectPool> Pools;
        public List<PooledObject> ObjectsToPool;

        private void Awake()
        {
            for (int i = 0; i < ObjectsToPool.Count; i++)
            {
                ObjectPool newPool = CreateNewPool(ObjectsToPool[i]);
                newPool.PreCreateObjects(3);                
            }
        }
        
        public ObjectPool CreateNewPool(PooledObject pooledObject)
        {
            var newPool = new ObjectPool();
            newPool.PooledObject = pooledObject;

            Pools.Add(newPool);

            return newPool;
        }

        public ObjectPool GetPool(PooledObject pooledObject)
        {
            ObjectPool toReturn = Pools.Find(pool => pool.PooledObject == pooledObject);

            if (toReturn == null)
                toReturn = CreateNewPool(pooledObject);

            return toReturn;
        }

        public PooledObject GetObject(PooledObject pooledObject)
        {
            return GetPool(pooledObject).GetObject();
        }
    }
}