using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.Events;

public class MainThreadWorker
{
    private static readonly object ExecuteLock = new object();
    public readonly static Queue<UnityEvent> ExecuteOnMainThread = new Queue<UnityEvent>();
    private const int MaxEventsPerFrame = 256;

    public static void Enqueue(UnityEvent evt)
    {
        if (evt == null)
            return;
        lock (ExecuteLock)
        {
            ExecuteOnMainThread.Enqueue(evt);
        }
    }


    public void Update()
    {
        int processed = 0;
        while (processed < MaxEventsPerFrame)
        {
            UnityEvent evt;
            lock (ExecuteLock)
            {
                if (ExecuteOnMainThread.Count == 0)
                    return;
                evt = ExecuteOnMainThread.Dequeue();
            }

            try
            {
                evt?.Invoke();
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
            }

            processed++;
        }

        Debug.LogWarning($"MainThreadWorker: budget exceeded, leaving {ExecuteOnMainThread.Count} events for next frame");
    }
}
