using System.Diagnostics;
using Luski;
using Luski.Classes;
using Luski.GUI;
using OpenTK.Windowing.Common.Input;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Image = OpenTK.Windowing.Common.Input.Image;

try
{
    Globals.Settings = Globals.GetSettings(Path.Combine(Globals.LuskiPath, "Settings.json"), SettingsContext.Default.Settings);
    foreach (ExperimentInfo le in LuskiExperiments.LuskiExperimentsList)
    {
        Globals.RegisterExperiment(le);
    }
    
    ServerList serverlist = Globals.GetSettings(Path.Combine(Globals.LuskiPath, "Servers.json"), ServerListContext.Default.ServerList);
    Globals.ServerList = serverlist;
    string themes = Path.Combine(Globals.LuskiPath, "Themes");
    if (!Directory.Exists(themes)) Directory.CreateDirectory(themes);
    DirectoryInfo di = new DirectoryInfo(themes);

    foreach (DirectoryInfo Theme in di.GetDirectories())
    {
        try
        {
            LuskiThemes.LoadThemeFromDir(Theme.FullName);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    foreach (FileInfo Theme in di.GetFiles())
    {
        try
        {
            if (Theme.FullName.ToLower().EndsWith(".zip")) LuskiThemes.LoadThemeFromDir(Theme.FullName);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    if (serverlist.Servers.Length > 0)
    {
        foreach (ServerInfo server in serverlist.Servers)
        {
            switch (server.Main)
            {
                case false:
                    Globals.ServersLoading.Add(Task.Run(async () =>
                    {
                        return await Globals.Luski.TryGetPublicServer(out _, server.Domain, server.Version,
                            server.Secure, server.PreGenEncryption, server.ShowMessage);
                    }));
                    break;
                case true:
                    if (LuskiExperiments.MainServers.EnableMainServers.IsEnabled()) Globals.Luski.GetMainServer(server.Domain, server.Version);
                    break;
            }
        }
    }
    Globals.UpdaterSettings = Globals.GetSettings(Path.Combine(Globals.LuskiPath, "UpdaterSettings.json"), UpdaterSettingsContext.Default.UpdaterSettings);
    if (Globals.UpdaterSettings.Updater is null) Globals.UpdaterSettings.Updater = string.Empty;
    Image<Rgba32> Logo = SixLabors.ImageSharp.Image.Load<Rgba32>(Globals.GetResource("Textures.Luski.png"));
    Logo.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> m);
    byte[] pixels = new byte[4 * Logo.Width * Logo.Height];
    Logo.CopyPixelDataTo(pixels);
   
    Globals.Icon = new WindowIcon(new Image(Logo.Width, Logo.Height, pixels));
    
    Logo.Dispose();
    Globals.ms = new MainScreenWindow();
    Globals.ms.CustomF11 = false;
    Globals.ms.DrawFrame();
    pixels = Array.Empty<byte>();
    Globals.ms.StartRender();
    Globals.ms.Dispose();
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

if (Globals.Download)
{
    Console.WriteLine("Auto Update Starting");
    List<string> arguments = new List<string>
    {
        "--process",
        Process.GetCurrentProcess().ProcessName,
        "--remotedirectory",
        "Luski",
        "--localdirectory",
        AppDomain.CurrentDomain.BaseDirectory,
        "--branch",
        "main",
        "--selfcontained",
        Globals.UpdaterSettings.SelfContained.ToString().ToLower(),
        "--platform",
        Globals.UpdaterSettings.Platform,
        "--setconfig",
        Path.Combine(Globals.LuskiPath, "UpdaterSettings.json")
    };
    if (Globals.UpdaterSettings.AutoLaunch)
    {
        arguments.Add("--dll");
        arguments.Add(AppDomain.CurrentDomain.FriendlyName);
    }
    Process p = new();
    p.StartInfo.FileName = Globals.UpdaterSettings.Updater;
    p.StartInfo.UseShellExecute = true;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.WorkingDirectory = new FileInfo(Globals.UpdaterSettings.Updater!).Directory!.FullName;
    p.StartInfo.Arguments = $"\"{string.Join("\" \"", arguments)}\"";
    p.Start();
    Environment.Exit(0);
}