using System;
using System.Collections.Generic;
using Decal.Adapter;

namespace MosswartMassacre
{
    public static class DelayedCommandManager
    {
        static List<DelayedCommand> delayedCommands = new List<DelayedCommand>();
        static bool isDelayListening = false;

        public static void AddDelayedCommand(string command, double delay)
        {
            var delayed = new DelayedCommand(command, delay);
            delayedCommands.Add(delayed);
            delayedCommands.Sort((x, y) => x.RunAt.CompareTo(y.RunAt));

            if (!isDelayListening)
            {
                isDelayListening = true;
                CoreManager.Current.RenderFrame += Core_RenderFrame_Delay;
            }
        }

        private static void Core_RenderFrame_Delay(object sender, EventArgs e)
        {
            try
            {
                while (delayedCommands.Count > 0 && delayedCommands[0].RunAt <= DateTime.UtcNow)
                {
                    // Use Decal_DispatchOnChatCommand to ensure other plugins can intercept
                    PluginCore.DispatchChatToBoxWithPluginIntercept(delayedCommands[0].Command);
                    delayedCommands.RemoveAt(0);
                }

                if (delayedCommands.Count == 0)
                {
                    CoreManager.Current.RenderFrame -= Core_RenderFrame_Delay;
                    isDelayListening = false;
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat("Error in delayed command system: " + ex.Message);
            }
        }
    }

    public class DelayedCommand
    {
        public string Command { get; set; }
        public double Delay { get; set; }
        public DateTime RunAt { get; set; }

        public DelayedCommand(string command, double delay)
        {
            Command = command;
            Delay = delay;
            RunAt = DateTime.UtcNow.AddMilliseconds(delay);
        }
    }
}
