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

public class PoolManager : MonoBehaviour
{
    public static PoolManager instance;
    public Dictionary<GameObject, List<GameObject>> pools;

    void Awake()
    {
        if (instance)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;

        pools = new Dictionary<GameObject, List<GameObject>>();
    }

    public static GameObject Instantiate(GameObject prefab, Vector3 pos = default, Quaternion rotation = default, Transform parent = null)
    {
        GameObject go;
        if (!instance)
        {
            go = Object.Instantiate(prefab, pos, rotation, parent);
            go.SetActive(true);
            return go;
        }
        if (instance.pools.ContainsKey(prefab) && instance.pools[prefab].Count > 0)
        {
            go = instance.pools[prefab][0];
            go.transform.parent = parent;
            go.transform.position = pos;
            go.transform.rotation = rotation;
            instance.pools[prefab].RemoveAt(0);
        }
        else
        {
            go = Object.Instantiate(prefab, pos, rotation, parent);
            PoolItem poolItem = go.AddComponent<PoolItem>();
            poolItem.prefab = prefab;
        }
        go.SetActive(true);
        return go;
    }

    public void Recycle(PoolItem poolItem)
    {
        if (!pools.ContainsKey(poolItem.prefab))
        {
            pools.Add(poolItem.prefab, new List<GameObject>());
        }
        pools[poolItem.prefab].Add(poolItem.gameObject);
    }

    public void DestroyItem(PoolItem poolItem)
    {
        if (!pools.ContainsKey(poolItem.prefab))
        {
            return;
        }
        pools[poolItem.prefab].Remove(poolItem.gameObject);
    }
}
