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

public class TimerManager : D_MonoSingleton<TimerManager>
{
    [SerializeField] int _TimerCount;

    private List<TimerUnit> mTimerList;
    private List<TimerUnit> mDestroyList;

    protected override void Initialize()
    {
        base.Initialize();

        mTimerList = new List<TimerUnit>();
        mDestroyList = new List<TimerUnit>();
    }

    private void Update()
    {
        _TimerCount = mTimerList.Count;
        if (mTimerList.Count > 0)
        {
            for (int i = 0; i < mTimerList.Count; i++)
            {
                if (mTimerList[i].IsAvailable)
                {
                    mTimerList[i].Update(Time.deltaTime, Time.unscaledDeltaTime);
                }
                else
                {
                    mDestroyList.Add(mTimerList[i]);
                }
            }

            if (mDestroyList.Count > 0)
            {
                for (int i = 0; i < mDestroyList.Count; i++)
                {
                    mTimerList.Remove(mDestroyList[i]);
                }

                mDestroyList.Clear();
            }
        }
    }

    public TimerUnit CreateTimerUnit()
    {
        TimerUnit tUnit = new TimerUnit();
        mTimerList.Add(tUnit);

        return tUnit;
    }

    public void Schedule(Action pDelDone, float pSeconds, int pCount = 1, bool pIgnoreTimeScale = false)
    {
        TimerUnit tUnit = CreateTimerUnit();
        tUnit.StartTimer(pDelDone, pSeconds, pCount, pIgnoreTimeScale, true);
    }

    public void DestroyTimerUnit(TimerUnit pUnit)
    {
        pUnit.Destroy();
    }

    public void ClearAll()
    {
        foreach (TimerUnit tUnit in mTimerList)
        {
            tUnit.Destroy();
        }
    }
}