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

namespace ChillConnect
{
    public class EasyTimer : MonoBehaviour
    {
        private Dictionary<Action, float> mIntervalDic = new();
        private List<Action> triggers = new();

        [SerializeField] private string timerName;
        private TimerTimeType type = TimerTimeType.Null;

        public void SetTimer(string name, TimerTimeType type)
        {
            timerName = name + "_" + type;
            this.type = type;
        }

        private float GetTime()
        {
            return type switch
            {
                TimerTimeType.Time => Time.time,
                TimerTimeType.UnscaledTime => Time.unscaledTime,
                TimerTimeType.RealtimeSinceStartup => Time.realtimeSinceStartup,
                _ => 0
            };
        }

        private void Update()
        {
            if (mIntervalDic.Count > 0)
            {
                triggers.Clear();
                foreach (var keyValue in mIntervalDic.Where(keyValue => keyValue.Value <= GetTime()))
                {
                    triggers.Add(keyValue.Key);
                }

                foreach (var func in triggers)
                {
                    mIntervalDic.Remove(func);
                    func();
                }
            }
        }

        public void AddTimer(float interval, Action func)
        {
            if (null != func)
            {
                if (interval <= 0)
                {
                    func();
                    return;
                }

                mIntervalDic[func] = GetTime() + interval;
            }
        }

        public void ClearAll()
        {
            mIntervalDic.Clear();
            triggers.Clear();
        }

        private void OnDestroy()
        {
            ClearAll();
            mIntervalDic = null;
            triggers = null;
        }
    }
}