using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
namespace Zerolauncher.Manager
{
    internal static class WebApiManager
    {
        static readonly HttpListener Listener = new HttpListener();
        static readonly CancellationTokenSource Cts = new CancellationTokenSource();
        public static async Task StartListener()
        {
            Listener.Prefixes.Add("http://127.0.0.1:7233/");
            Listener.Start();
            Trace.WriteLine("Listening...");

            while (!Cts.Token.IsCancellationRequested)
            {
                var context = await Listener.GetContextAsync();
                var request = context.Request;
                var response = context.Response;
                var raw = request.RawUrl;
                ResponseBody? rb = null;
                if (raw != null && raw.Contains("?")) 
                {
                    var lines = raw.Split("?");
                    var args = request.QueryString;
                    var nick = args["name"];
                    if (nick != null)
                    {
                        var acc = TeamManager.Nick2Acc(nick);
                        if (acc != null)
                        {
                            switch (lines[0])
                            {
                                case "/CloseGame":
                                {
                                    rb = EngineManager.ExitGame(acc) ? new ResponseBody(1, 0, $"Account [{nick}] successful to close.") : new ResponseBody($"Account [{nick}] is unluacher.");
                                }
                                    break;
                                case "/ToNormalSize":
                                {
                                    rb = EngineManager.TurnGameSizeNormal(acc) switch
                                    {
                                        2 => new ResponseBody(1, 0, $"Account [{nick}] now is normal size."),
                                        1 => new ResponseBody(0, 0, $"Account [{nick}] is loading, please wait."),
                                        0 => new ResponseBody($"Account [{nick}] is unluacher."),
                                        _ => rb
                                    };
                                }
                                    break;
                                case "/ToMiniSize":
                                {
                                    rb = EngineManager.TurnGameSizeMini(acc) switch
                                    {
                                        2 => new ResponseBody(1, 0, $"Account [{nick}] now is mini size."),
                                        1 => new ResponseBody(0, 0, $"Account [{nick}] is loading, please wait."),
                                        0 => new ResponseBody($"Account [{nick}] is unluacher."),
                                        _ => rb
                                    };
                                }
                                    break;
                                case "/LoginGame":
                                    {
                                        if (EngineManager.CreateGame(acc))
                                        {
                                            rb = new ResponseBody(0, 0, $"Account [{nick}] successful to start.");
                                        }
                                        else
                                        {
                                            var hwnd = EngineManager.CheckGameState(acc);
                                            rb = hwnd <= 0 ? new ResponseBody(0, 0, $"Account [{nick}] is loading, please wait.") : new ResponseBody(1, hwnd, $"Account [{nick}] now is running.");
                                        }
                                    }
                                    break;
                                default:
                                    rb = new ResponseBody($"commad [{lines[0]}] undefind.");
                                    break;
                            }
                        }
                        else
                        {
                            rb = new ResponseBody($"Account [{nick}] undefind.");
                        }
                    }
                    else
                    {
                        rb = new ResponseBody("args is missing.");
                    }

                }
                rb ??= new ResponseBody();
                var buffer = Encoding.UTF8.GetBytes(rb.Encode());

                response.ContentLength64 = buffer.Length;
                var output = response.OutputStream;
                await output.WriteAsync(buffer, 0, buffer.Length);
                output.Close();
            }
            Listener.Stop();
        }

        public static void StopListener() { Cts.Cancel(); }
    }

    class ResponseBody(int status = -1, int hwnd = 0, string message = "Hello, World!")
    {
        public ResponseBody(string message) : this(-1, 0, message)
        {
        }

        public string Encode()
        {
            return $"{{\"state\": {status}, \"hwnd\": {hwnd}, \"message\": \"{message}\"}}";
        }
    }
}
