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

namespace JLGames.RocketDriver.Actions.ThreadEvent
{
    public sealed class MonoEventProxy : MonoBehaviour
    {
        [SerializeField] private bool m_ProxyEnabled = true;
        private readonly Queue<Action> m_Actions = new Queue<Action>();

        public void SetProxyEnable(bool proxyEnabled)
        {
            m_ProxyEnabled = proxyEnabled;
        }

        public void ExecInMain(Action action)
        {
            lock (m_Actions)
            {
                m_Actions.Enqueue(action);
            }
        }

        private void FixedUpdate()
        {
            if (!m_ProxyEnabled) return;

            if (ThreadEventRecords.HaveEvents)
            {
                ThreadEventRecords.HandleEvents();
            }

            lock (m_Actions)
            {
                while (m_Actions.Count > 0)
                {
                    m_Actions.Dequeue().Invoke();
                }
            }
        }
    }
}