using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Decal.Adapter;

namespace MosswartMassacre
{
    public static class HttpCommandServer
    {
        private static HttpListener listener;
        private static CancellationTokenSource cts;
        private static bool isRunning = false;

        public static bool IsRunning => isRunning;

        public static void Start()
        {
            if (isRunning) return;

            try
            {
                listener = new HttpListener();
                listener.Prefixes.Add("http://localhost:8085/");
                listener.Start();
                cts = new CancellationTokenSource();
                Task.Run(() => ListenLoop(cts.Token));

                isRunning = true;
                PluginCore.WriteToChat("[HTTP] Server started on port 8085.");
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat("[HTTP] Error starting server: " + ex.Message);
            }
        }

        public static void Stop()
        {
            if (!isRunning) return;

            try
            {
                cts.Cancel();
                listener.Stop();
                listener.Close();
                listener = null;
                isRunning = false;
                PluginCore.WriteToChat("[HTTP] Server stopped.");
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat("[HTTP] Error stopping server: " + ex.Message);
            }
        }

        private static async Task ListenLoop(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                HttpListenerContext context = null;

                try
                {
                    context = await listener.GetContextAsync();
                }
                catch (HttpListenerException)
                {
                    break; // Listener was stopped
                }

                if (context == null) continue;

                string requestBody = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();

                PluginCore.WriteToChat("[HTTP] Received request: " + requestBody);

                // Parse simple format: target=Name&command=/say hello
                string target = "";
                string command = "";
                foreach (var pair in requestBody.Split('&'))
                {
                    var parts = pair.Split('=');
                    if (parts.Length == 2)
                    {
                        if (parts[0] == "target") target = WebUtility.UrlDecode(parts[1]);
                        else if (parts[0] == "command") command = WebUtility.UrlDecode(parts[1]);
                    }
                }

                if (!string.IsNullOrWhiteSpace(target) && !string.IsNullOrWhiteSpace(command))
                {
                    string tellCmd = $"/a {target} {command}";
                    CoreManager.Current.Actions.InvokeChatParser(tellCmd);
                }

                byte[] buffer = Encoding.UTF8.GetBytes("Command received.");
                context.Response.ContentLength64 = buffer.Length;
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.OutputStream.Close();
            }
        }
    }
}
