﻿using UnityEngine;
using System.Collections.Generic;

namespace creXa.GameBase
{
    /// <summary>
    /// Setting Up List to Gather Objects Under the Same Parent
    /// </summary>
    /// <typeparam name="T">Should be the current class</typeparam>
    /// <typeparam name="U">Monobehaviour under this root</typeparam>
    public abstract class ZRoot<T, U> : ZSingleton<T> where T : MonoBehaviour where U : MonoBehaviour
    {
        public GameObject spwanObject;
        protected List<U> items = new List<U>();

        public delegate void OnListRemovedDel();
        public static OnListRemovedDel OnListRemoved;

        public delegate void OnListAddedDel();
        public static OnListAddedDel OnListAdded;

        public void Add(U item, Vector3? defaultPos = null)
        {
            if (items.Contains(item)) return;

            items.Add(item);
            item.transform.SetParent(transform);
            item.transform.localScale = Vector3.one;
            item.transform.localPosition = defaultPos.HasValue ? (Vector3)defaultPos : Vector3.zero;

            if (OnListAdded != null) OnListAdded();
        }

        public U Add(Vector3? defaultPos = null)
        {
            if (spwanObject == null) return null;
            GameObject tmp = Instantiate(spwanObject);
            tmp.transform.SetParent(transform);
            tmp.transform.localScale = Vector3.one;
            U item = tmp.GetComponent<U>();
            items.Add(item);

            if (OnListAdded != null) OnListAdded();

            return item;
        }

        public void DestroyAll()
        {
            for (int i = 0; i < items.Count; i++)
                DestroyImmediate(items[i].gameObject);

            items = new List<U>();
        }
        
        public void Remove(U item, bool DESTROY = false)
        {
            if(!items.Contains(item)) return;
            items.Remove(item);

            if (DESTROY && item) DestroyImmediate(item.gameObject);
            if (OnListRemoved != null) OnListRemoved();
        }

        public U[] GetItems()
        {
            return items.ToArray();
        }
    }
}
