using System;

public class TimerUnit
{
    public bool IsRunning => mStarted;
    public bool IsAvailable => !mDestroyed;

    private Action mDelDone;

    private bool mStarted = false;
    private bool mDestroyed = false;

    private float mTotalTime;
    private float mTimeCounter = -1;
    private int mCount = 0;

    private bool mIgnoreTimeScale = false;
    private bool mAutoDestroy = false;

    public void Update(float pDeltaTime, float pUnscaledDeltaTime)
    {
        if (mStarted)
        {
            if (mTimeCounter > 0)
            {
                mTimeCounter -= mIgnoreTimeScale ? pUnscaledDeltaTime : pDeltaTime;
                if (mTimeCounter <= 0)
                {
                    Done();
                }
            }
        }
    }

    public void StartTimer(Action pDelDone, float pSeconds, int pCount = 1, bool pIgnoreTimeScale = false, bool pAutoDestroy = false)
    {
        mDelDone = pDelDone;

        mTotalTime = pSeconds;
        mCount = pCount;
        mIgnoreTimeScale = pIgnoreTimeScale;
        mAutoDestroy = pAutoDestroy;

        if (pSeconds <= 0)
        {
            Done();
        }
        else
        {
            ExecuteOnce();
        }
    }

    public void CancelTimer()
    {
        mStarted = false;
        mTotalTime = 0;
        mTimeCounter = -1;

        mDelDone = null;
    }

    public void ResetTimeDelta(float pSeconds)
    {
        mTotalTime = pSeconds;
    }

    public void ReUse()
    {
        mDestroyed = false;
    }

    public void Destroy()
    {
        mStarted = false;
        mDestroyed = true;
    }

    private void ExecuteOnce()
    {
        mStarted = true;
        mTimeCounter = mTotalTime;
    }

    private void Done()
    {
        mStarted = false;
        mDelDone?.Invoke();

        mCount--;
        if (mCount > 0)
        {
            ExecuteOnce();
        }
        else
        {
            if (mAutoDestroy)
            {
                Destroy();
            }
        }
    }
}