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

namespace ChillConnect
{
    internal class AsyncKitUnityBehaviour : SingletonUnity<AsyncKitUnityBehaviour>
    {
        private readonly Dictionary<string, AsyncDealData> _asyncDataDict = new Dictionary<string, AsyncDealData>();


        private readonly Dictionary<string, AsyncDealData> _updateActionDict = new Dictionary<string, AsyncDealData>();

        private readonly List<string> _keyClean = new List<string>();

        private void Update()
        {
            foreach (var temp in _asyncDataDict.Values)
            {
                temp.PassTime(Time.deltaTime);
            }

            try
            {
                foreach (var temp in _updateActionDict.Values)
                {
                    temp?.dealMethod?.Invoke();
                }
            }
            catch (Exception)
            {
            }


            ClearFinished();


            ClearUpdateActionFinished();
        }


        private void ClearFinished()
        {
            _keyClean.Clear();
            foreach (var dealData in _asyncDataDict)
            {
                if (dealData.Value.IsComplete)
                {
                    _keyClean.Add(dealData.Key);
                }
            }

            foreach (var key in _keyClean)
            {
                _asyncDataDict.Remove(key);
            }
        }


        public void AddAsyncData(string key, AsyncDealData asyncDealData)
        {
            RemoveAsyncData(key);
            _asyncDataDict.Add(key, asyncDealData);
        }


        public void RemoveAsyncData(string key)
        {
            if (_asyncDataDict.ContainsKey(key))
            {
                _asyncDataDict.Remove(key);
            }
        }

        public void ClearUpdateActionFinished()
        {
            _keyClean.Clear();
            foreach (var dealData in _updateActionDict)
            {
                if (dealData.Value.IsComplete)
                {
                    _keyClean.Add(dealData.Key);
                }
            }

            foreach (var key in _keyClean)
            {
                _updateActionDict.Remove(key);
            }
        }
    }
}