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

public static class Pool
{
    public class Able : MonoBehaviour
    {
        public GameObject template;
    }

    public static readonly Dictionary<GameObject, HashSet<GameObject>> inactive = new Dictionary<GameObject, HashSet<GameObject>>();

    public static HashSet<GameObject> Inactive(GameObject template)
    {
        HashSet<GameObject> set;
        if (inactive.TryGetValue(template, out set))
            return set;
        return inactive[template] = new HashSet<GameObject>();
    }

    public static GameObject Get(GameObject template, Vector3 position, Quaternion rotation)
    {
        return Object.Instantiate(template, position, rotation);
        // if (!template)
        // {
        //     Debug.LogWarning("Attempting to pool using NULL Template: Do nothing");
        //     return null;
        // }

        // var set = Inactive(template);

        // GameObject obj = set.FirstOrDefault();
        // if (!obj)
        //     obj = GameObject.Instantiate(template, position, rotation);

        // var comp = obj.GetOrAddComponent<Able>();
        // comp.template = template;

        // obj.SetActive(true);
        // set.Remove(obj);

        // return obj;
    }
    public static GameObject Get(GameObject template, Vector3 position)
    {
        return Get(template, position, Quaternion.identity);
    }
    public static GameObject Get(GameObject template, Quaternion rotation)
    {
        return Get(template, Vector3.zero, rotation);
    }
    public static GameObject Get(GameObject template)
    {
        return Get(template, Vector3.zero, Quaternion.identity);
    }

    public static void Del(GameObject obj)
    {
        // if (!obj)
        // {
        //     Debug.LogWarning("Attempting to unpool NULL GameObject: Do nothing");
        //     return;
        // }

        // var elem = obj.GetComponent<Able>();
        // if (elem && elem.template)
        // {
        //     obj.SetActive(false);
        //     Inactive(elem.template).Add(obj);
        //     return;
        // }

        // if (!elem)
        //     Debug.LogWarning("GameObject (" + obj.name + ") is not a PoolObject: Destroying instead");
        // else if (!elem.template)
        //     Debug.LogWarning("GameObject (" + obj.name + ") has missing Template: Destroying instead");

        GameObject.Destroy(obj);
    }
    public static void Del(GameObject obj, float delay)
    {
        DelayedAction.Schedule(delay, () => Del(obj));
    }
}
