using System;
using System.Collections.Generic;
using System.Timers;

namespace _Combo
{
    public class CountdownTimer
    {
        private event Action OnCountdownFinished;    
        private Timer timer;
        private float countdownTime;
        private static Dictionary<string, CountdownTimer> timerMap = new Dictionary<string, CountdownTimer>();
        private static List<string> subscriptionList = new List<string>();

        public static CountdownTimer GetInstance(string key, float timeInSeconds)
        {
            if (timerMap.ContainsKey(key))
            {
                var existingTimer = timerMap[key];
                existingTimer.Reset(timeInSeconds);
                return existingTimer;
            }
            else
            {
                var newTimer = new CountdownTimer(timeInSeconds);
                timerMap[key] = newTimer;
                return newTimer;
            }
        }

        public static CountdownTimer GetInstance(string key)
        {
            if (timerMap.ContainsKey(key))
            {
                var existingTimer = timerMap[key];
                return existingTimer;
            }
            else
            {
                return null;
            }
        }

        private CountdownTimer(float timeInSeconds)
        {
            countdownTime = timeInSeconds;
            timer = new Timer(1000); // 每秒触发一次
            timer.Elapsed += OnTimerElapsed;
        }

        public void SubscribeOnCountdownFinished(string key, Action action)
        {
            if (subscriptionList.Contains(key))
            {
                return;
            }
            subscriptionList.Add(key);
            OnCountdownFinished += action;
        }

        public void UnsubscribeOnCountdown(string key, Action action)
        {
            if (subscriptionList.Contains(key))
            {
                subscriptionList.Remove(key);
                OnCountdownFinished -= action;
            }
        }

        private void Reset(float timeInSeconds)
        {
            countdownTime = timeInSeconds;
            if (timer.Enabled)
            {
                timer.Stop();
                timer.Start();
            }
        }

        public void Start()
        {
            timer.Start();
            TempDispatcher.Initialize();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            countdownTime -= 1f;

            if (countdownTime <= 0)
            {
                timer.Stop();
                TempDispatcher.RunOnMainThread(() =>
                {
                    OnCountdownFinished?.Invoke();
                });
            }
        }
    }
}