// Copyright (c) 2025 TerraByte Inc.
//
// A static manager that hooks into the Unity Editor's update loop to process
// promises, ensuring their callbacks are executed on the main thread.

using UnityEditor;
using System.Collections.Generic;

namespace Terra.Arbitrator.Promises
{
    [InitializeOnLoad] // Ensures the static constructor is called when the editor loads.
    public static class PromiseManager
    {
        private static readonly List<ITrackablePromise> PendingPromises = new();

        static PromiseManager()
        {
            EditorApplication.update -= Update; // Ensure we don't get duplicate subscriptions on recompile
            EditorApplication.update += Update;
        }

        private static void Update()
        {
            // Lock to prevent modification while iterating, in case a callback adds another promise.
            lock (PendingPromises)
            {
                // Iterate backwards so we can safely remove items.
                for (var i = PendingPromises.Count - 1; i >= 0; i--)
                {
                    // The Tick() method on the promise will return true when it's finished.
                    // We use dynamic here to call Tick() without knowing the generic type of the promise.
                    if (PendingPromises[i].Tick())
                    {
                        PendingPromises.RemoveAt(i);
                    }
                }
            }
        }

        /// <summary>
        /// Registers a new promise to be ticked by the manager.
        /// </summary>
        public static void Track(ITrackablePromise promise)
        {
            lock (PendingPromises)
            {
                PendingPromises.Add(promise);
            }
        }
    }
}