using System;
using System.Collections.Generic;
using System.Threading;
using _Core;
using UnityEngine;
namespace _Combo
{
    public class TempDispatcher : MonoBehaviour {
        
        private static List<Action> _actions = new List<Action>(8);
        private static List<Action> _backlog = new List<Action>(8);
        private static TempDispatcher _instance;
        private static int _mainThreadId;
        private static volatile bool _queued = false;

        public static bool CurrentlyOnMainThread {
            get {
                if (_mainThreadId == 0) {
                    return true;
                }
                return Thread.CurrentThread.ManagedThreadId == _mainThreadId;
            }
        }

        public static void Initialize()
        {
            if (_instance == null) {
                _mainThreadId = Thread.CurrentThread.ManagedThreadId;
                _instance = new GameObject("ComboSDK.TempDispatcher").AddComponent<TempDispatcher>();
                DontDestroyOnLoad(_instance.gameObject);
            }
        }

        public static void RunOnMainThread(Action action) {

            if (CurrentlyOnMainThread) {
                action();
                return;
            }
            lock(_backlog) {
                _backlog.Add(action);
                _queued = true;
            }
        }

        void Update() {

            if (_queued) {
                lock(_backlog) {
                    var tmp = _actions;
                    _actions = _backlog;
                    _backlog = tmp;
                    _queued = false;
                }

                foreach (var action in _actions) {
                    try {
                        action();
                    } catch (Exception e) {
                       Log.E(e);
                    }
                }
                _actions.Clear();
            }
        }

    }
}