#if !COMBAT_SERVER
using System.Collections.Generic;
using UnityEngine;
using Utility;

namespace CombatLibrary.CombatLibrary.CombatCore.Utility
{
    public class GameObjectDestroyPool : Singleton<GameObjectDestroyPool>
    {
        private BetterList<GameObject> pool = new BetterList<GameObject>();

        private List<GameObject> _removeGameObjecet = new List<GameObject>();
        public GameObjectDestroyPool()
        {
            StaticUpdater.Instance.AddRenderUpdateCallBack(UpdateDelete);
        }

        private int maxCount =1;

        public void RomoveDestroyObject(GameObject goObj)
        {
            if (pool.Contains(goObj))
            {
                pool.Remove(goObj);
            }
            if (_removeGameObjecet.Contains(goObj))
            {
                _removeGameObjecet.Remove(goObj);
            }
        }

        public void DestroyObject(GameObject goObj)
        {
            if (pool.Contains(goObj)||goObj==null)
            {
                return;
            }

            goObj.SetActive(false);
            pool.Add(goObj);
        }

        public void ImmediatelyDestroyObject(GameObject goObj)
        {
            if (!goObj)
            {
                return;
            }

            GameObject.Destroy(goObj);
        }

        public override void Dispose()
        {
            StaticUpdater.Instance.RemoveRenderUpdateCallBack(UpdateDelete);
            for (int i = 0; i < pool.Count; i++)
            {
                ImmediatelyDestroyObject(pool[i]);
            }

            pool.Clear();
            base.Dispose();
        }

        public void UpdateDelete()
        {
            _removeGameObjecet.Clear();
            int count = 0;
            for (int i = 0; i < pool.Count; i++)
            {
                if (count <= maxCount)
                {
                    _removeGameObjecet.Add(pool[i]);
                    pool.RemoveAt(i);
                    i--;
                    count++;
                }
            }

            int removeCount = 0;
            while (_removeGameObjecet.Count>0&&removeCount<maxCount+20)
            {
                removeCount++;
                GameObject g = _removeGameObjecet[0];
                ImmediatelyDestroyObject(g);
                _removeGameObjecet.RemoveAt(0);
            }
         
        }
    }
}
#endif