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

namespace mgaia.Utils
{
    /// <summary>
    /// Classe que agenda ações para acontecerem no próximo frame
    /// </summary>
    /// <owner>Victor</owner>
    public static class NextFrameScheduler
    {
        private static GameTimeBridgeBehaviour sGameTimeBridge;
        private static List<NextFrameSchedulePayload> sSchedules = new List<NextFrameSchedulePayload>();

        /// <summary>
        /// Cria o scheduler
        /// </summary>
        public static void Create()
        {
            GameObject gameObject = new GameObject(Constants.NEXT_FRAME_SCHEDULER_NAME);
            gameObject.isStatic = true;
            GameObject.DontDestroyOnLoad(gameObject);

            sGameTimeBridge = gameObject.AddComponent<GameTimeBridgeBehaviour>();
            sGameTimeBridge.Initialize(Update, FixedUpdate);
        }

        private static void Update(float time)
        {
            List<NextFrameSchedulePayload> payloadsToRemove = new List<NextFrameSchedulePayload>();
            int currentFrameCount = Time.frameCount;

            foreach (NextFrameSchedulePayload frameSchedulePayload in sSchedules)
            {
                if (currentFrameCount != frameSchedulePayload.RegisteredFrameCount)
                {
                    frameSchedulePayload.Action();
                    payloadsToRemove.Add(frameSchedulePayload);
                }
            }

            foreach (NextFrameSchedulePayload frameSchedulePayload in payloadsToRemove)
            {
                sSchedules.Remove(frameSchedulePayload);
            }
        }

        private static void FixedUpdate(float time)
        {
        }

        /// <summary>
        /// Adiciona uma ação para ser executada no próximo frame
        /// </summary>
        public static void Schedule(Action action)
        {
            sSchedules.Add(new NextFrameSchedulePayload(action, Time.frameCount));
        }
    }
}