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

namespace Assets.Scripts.Utils
{
    public class ObjectPool
    {
        public GameObject PooledObject;
        public List<GameObject> Pool;
        public bool WillGrow;
        public int Size;

        public ObjectPool(int size)
        {
            Size = size;
            Pool = new List<GameObject>();

            for (var i = 0; i < Pool.Count; i++)
            {
                var obj = Object.Instantiate(PooledObject);

                obj.SetActive(false);
                Pool.Add(obj);
            }
        }

        public GameObject GetPooledObject()
        {
            if (!WillGrow || !Pool.All(o => o.activeInHierarchy))
                return Pool.FirstOrDefault(o => !o.activeInHierarchy);

            var obj = Object.Instantiate(PooledObject);

            Pool.Add(obj);
            return obj;
        }
    }
}