using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using GraphicsManager.Enums;
using GraphicsManager.Globals;
using GraphicsManager.Interfaces;
using GraphicsManager.Objects;
using GraphicsManager.Objects.Core;
using Luski.GUI.MainScreen.UI;
using Luski.GUI.MainScreen.UI.PublicServers;
using Luski.net;
using Luski.net.Structures.Public;
using OpenTK.Graphics.GL;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;
using DebugProc = OpenTK.Graphics.OpenGL4.DebugProc;
using DebugSeverity = OpenTK.Graphics.OpenGL4.DebugSeverity;
using DebugSource = OpenTK.Graphics.OpenGL4.DebugSource;
using DebugType = OpenTK.Graphics.OpenGL4.DebugType;
using Window = GraphicsManager.Window;

namespace Luski.GUI;

public class MainScreenWindow : Window
{
    public static readonly NativeWindowSettings Settings = new()
    {
        Title = "Luski",
        WindowBorder = WindowBorder.Resizable,
        APIVersion = new Version(3, 2),
        API = ContextAPI.OpenGL,
        StartFocused = true,
        Size = new Vector2i(624, 1090),
        Icon = Globals.Icon,
        SharedContext = null,
    };

    public TabControl? tc;
    private FlowLayout? channelpicker, friends, friend_request;
    private RoundedButton? FriendManagerBtn;
    private static DebugProc DebugMessageDelegate = OnDebugMessage;

    private static void OnDebugMessage(
        DebugSource source, // Source of the debugging message.
        DebugType type, // Type of the debugging message.
        int id, // ID associated with the message.
        DebugSeverity severity, // Severity of the message.
        int length, // Length of the string in pMessage.
        IntPtr pMessage, // Pointer to message string.
        IntPtr pUserParam) // The pointer you gave to OpenGL, explained later.
    {
        string message = Marshal.PtrToStringAnsi(pMessage, length);

        switch (severity)
        {
            case DebugSeverity.DebugSeverityHigh:
                if ((Globals.Settings.Logs & ConsoleLog.BigErrosForOpenGL) == ConsoleLog.BigErrosForOpenGL)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("[{0} source={1} type={2} id={3}] {4}", severity, source, type, id, message);
                    Console.ResetColor();
                }

                break;
            case DebugSeverity.DebugSeverityMedium:
                if ((Globals.Settings.Logs & ConsoleLog.MediumErrosForOpenGL) == ConsoleLog.MediumErrosForOpenGL)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("[{0} source={1} type={2} id={3}] {4}", severity, source, type, id, message);
                    Console.ResetColor();
                }
                break;
            case DebugSeverity.DebugSeverityLow:
                if ((Globals.Settings.Logs & ConsoleLog.LowErrosForOpenGL) == ConsoleLog.LowErrosForOpenGL)
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("[{0} source={1} type={2} id={3}] {4}", severity, source, type, id, message);
                    Console.ResetColor();
                }
                break;
            default:
                if ((Globals.Settings.Logs & ConsoleLog.InfoForOpenGL) == ConsoleLog.InfoForOpenGL)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine(message);
                    Console.ResetColor();
                }
                break;
        }
    }
    

    public MainScreenWindow() : base(Settings)
    {
        Globals.ms = this;
        Size = new(1332.ScaleInt(), 866.ScaleInt());
        ShowMissingChar = true;
        LogFrames = ((Globals.Settings.Logs & ConsoleLog.DrawFrames) == ConsoleLog.DrawFrames);
        VSync = VSyncMode.On;

        GL.DebugMessageCallback(DebugMessageDelegate, IntPtr.Zero);
        GL.Enable(EnableCap.DebugOutput);
        try
        {
            Globals.DefaultFontFamly = FontFamily.LoadFontFamily(Globals.GetResource("Fonts.OpenSans.zip"), "OpenSans");
            Globals.DefaultFont = FontInteraction.Load(Globals.DefaultFontFamly);
            string fams = Path.Combine(Globals.LuskiPath, "FontFamilies");
            if (!Directory.Exists(fams)) Directory.CreateDirectory(fams);
            DirectoryInfo di = new DirectoryInfo(fams);
            
            foreach (FileInfo fam in di.GetFiles())
            {
                try
                {
                    if (fam.FullName.ToLower().EndsWith(".zip"))
                        Globals.DefaultFont.AddFamily(FontFamily.LoadFontFamily(File.Open(fam.FullName, FileMode.Open), fam.Name));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }


        Globals.DefaultFont.PixelHeight = Globals.Settings.DefaultFontPX.ScaleFont();
        Globals.DefaultFont.FontSize = FontSize.Regular;
        Globals.TopTimeFont = Globals.DefaultFont.Clone();
        Globals.TopTimeFont.PixelHeight = Globals.Settings.TopTimeFonttPX.ScaleFont();
        Globals.TopTimeFont.FontSize = FontSize.Regular;
        Globals.MessageFont = Globals.DefaultFont.Clone();
        Globals.MessageFont.PixelHeight = Globals.Settings.MessageFontPX.ScaleFont();
        Globals.MessageFont.ExtraLinePixels = Globals.Settings.MessageFontLineSpacePX.ScaleFont();
        Globals.MessageFont.FontSize = FontSize.Regular;
        Globals.SmallTimeFont = Globals.DefaultFont.Clone();
        Globals.SmallTimeFont.PixelHeight = ((uint)11).ScaleFont();
        Globals.LuskiTexture = TextureManager.GetTextureResource("Luski.png");
        try
        {
            CenterWindow(Globals.Settings.Display);
        }
        catch (Exception e)
        {
            CenterWindow();
        }
        WindowLoaded += OnWindowLoaded;
    }

    private async Task OnWindowLoaded(Window arg)
    {
        if (Globals.UpdaterSettings.AutoUpdateCheck && new HttpClient()
                .GetAsync(
                    $"https://www.jacobtech.com/Updater/GetProgramVersion?directory=Luski&branch=main&selfcontained={Globals.UpdaterSettings.SelfContained.ToString().ToLower()}&platform={Globals.UpdaterSettings.Platform}")
                .Result.Content.ReadAsStringAsync().Result !=
            FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion)
        {
            var update = new UpdateWindow();
            var result = update.ShowDialogue(this);
            if (result == UpdateWindow.DialogueResult.Yes)
            {
                Globals.Download = true;
                Close();
            }
        }
        await LoginOnChangeToApp();
    }
    
    public FlowLayout ser;
    private UserControl? SerBox;
    public PublicChat pc;

    public async Task LoadPublicServer(PublicServer? Server)
    {
        GL.Enable(EnableCap.DepthTest);
        GL.Enable(EnableCap.Multisample);
        GL.DepthFunc(DepthFunction.Always);
        if (Server is null) return;
        if (!Server.IsLogedIn)
        {
            ServerLoginOverlay SLO = new(Server.Domain);
            Controls.Add(SLO);
            ForceUpdate(new(ClientSize));
            Globals.PrintParent(this);
            return;
        }
        BlockDraw = true;
        try
        {
            #region Box Init

            if (SerBox is null)
            {
                SerBox = new()
                {
                    Location = new(ser.Size.X, 0, 0),
                    Size = new(Size.X - ser.Size.X, ClientSize.Y),
                    Anchor = ObjectAnchor.All,
                    BackgroundColor = new(20, 20, 20, 255)
                };
                Controls.Add(SerBox);
                SerBox.LoadToParent(this, this);
            }

            SerBox.Controls.Clear();

            #endregion
            
            #region Channel Selector Init

            SocketChannel current_channel = await Server.User.GetSelectedChannel(CancellationToken.None);
            List<SocketCategory> parents = new();
            SocketCategory? cur = await current_channel.GetParent();
            while (cur is not null)
            {
                parents.Add(cur);
                cur = await cur.GetParent();
            }

            parents.Reverse();
            ChannelSelector cs = await ChannelSelector.MakeSelector(parents[0]);
            cs.BackgroundColor = new(34, 34, 34, 255);
            cs.Size = new(307.ScaleInt(), SerBox.Size.Y - 54.ScaleInt());
            cs.Anchor = ObjectAnchor.Top | ObjectAnchor.Left | ObjectAnchor.Bottom;
            
            parents.RemoveAt(0);
            SerBox.Controls.Add(cs);
            cs.ForceDistanceUpdate(SerBox);

            #endregion

            #region Chat Init

            pc = new()
            {
                Anchor = ObjectAnchor.All,
                Location = new(cs.Size.X, 0, 0),
                Size = new(SerBox.Size.X - cs.Size.X, SerBox.Size.Y),
            };
            SerBox.Controls.Add(pc);
            pc.LoadToParent(SerBox, this);
            pc.ForceDistanceUpdate();
            pc.MessageFlow.ForceDistanceUpdate(pc);
            #endregion

            #region Channel Selector Loader

            _ = cs.Load(current_channel, parents);

            #endregion

            #region User Icon
            Role[] ra = await Server.User.GetRoles();
            Color c = ra[0].Color;
            Color4 c4 = new(c.R, c.G, c.B, c.A);
            ServerProfile DefaultProfile = await Server.GetProfile(Server.User.ServerProfile, CancellationToken.None);
            IRenderObject u = await DefaultProfile.MakeRct(Server.User, new(46.ScaleInt()));
            int ii = 4.ScaleInt();
            u.Location = new(ii, cs.Size.Y + ii, 0);
            u.Anchor = ObjectAnchor.Bottom | ObjectAnchor.Left;
            SerBox.Controls.Add(u);
            u.LoadToParent(SerBox, this);
            u.ForceDistanceUpdate();
            Label ul = new Label(Globals.DefaultFont)
            {
                Anchor = u.Anchor,
                Text = DefaultProfile.DisplayName,
                Color = c4
            };

            ul.Location = new(u.Location.X + u.Size.X + 5.ScaleInt(),
                (u.Location.Y + ((u.Size.Y - ul.Size.Y) / 2)), 0);
            SerBox.Controls.Add(ul);
            Rectangle setting = new(TextureManager.GetTextureResource("settings.png"))
            {
                Location = new(cs.Size.X - 40.ScaleInt(), cs.Size.Y + 11.ScaleInt(),0),
                Size = new(32.ScaleInt()),
                Shader = Rectangle.DefaultAlphaShader[Context],
                BackgroundColor = Color4.Gray,
                Anchor = ObjectAnchor.Bottom | ObjectAnchor.Left
            };
            setting.MouseEnter += o =>
            {
                setting.BackgroundColor = Color4.White;
                return Task.CompletedTask;
            };
            setting.MouseLeave += o =>
            {
                setting.BackgroundColor = Color4.Gray;
                return Task.CompletedTask;
            };
            setting.Clicked += SettingOnClicked;
            setting.ForceDistanceUpdate(SerBox);
            SerBox.Controls.Add(setting);
            ForceUpdate(new (Size));
            TryDraw();
            #endregion
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        BlockDraw = false;
    }

    private Task SettingOnClicked(IRenderObject arg)
    {
        SettingsMenu sm = new();
        Controls.Add(sm);
        Globals.ms.DrawFrame();
        return Task.CompletedTask;
    }

    public async Task LoadMainServer(MainServer Server)
    {
        if (SerBox is null)
            SerBox = new()
            {
                Location = new(ser.Size.X, 0, 0),
                Size = new(Size.X - ser.Size.X, Size.Y),
                Anchor = ObjectAnchor.All
            };
        Controls.Add(SerBox);
        SerBox.ForceDistanceUpdate();
        SerBox.Controls.Clear();
    }

    private async Task<Task> LoginOnChangeToApp()
    {
        Controls.Clear();
        BlockDraw = true;
        Title = "Luski";
        unsafe
        {
            GLFW.SetWindowSizeLimits(WindowPtr, 500.ScaleInt(), 250.ScaleInt(),GLFW.DontCare, GLFW.DontCare);
        }
        
        try
        {
            CenterWindow(Globals.Settings.Display);
        }
        catch (Exception e)
        {
            CenterWindow();
        }
        WindowBorder = WindowBorder.Resizable;
        BackgroundColor = new Color4(20, 20, 20, 255);

        Controls.Add(ser = new FlowLayout()
        {
            BackgroundColor = new(26, 26, 26, 255),
            Size = new(68.ScaleInt(), ClientSize.Y),
            Anchor = ObjectAnchor.Top | ObjectAnchor.Left | ObjectAnchor.Bottom,
            Location = new(0,0,0)
        });
        ser.LoadToParent(this,this);
        DrawFrame();
        DateTime utcNow = DateTime.UtcNow;
        Task.WhenAll(Globals.ServersLoading.ToArray()).Wait();
        foreach (PublicServer pser in Globals.Luski.LoadedServers)
        {
            ServerIcon<PublicServer> si = new ServerIcon<PublicServer>(pser);
            ser.Controls.Add(si);
            si.LoadToParent(ser, this);
        }

        AddServerIcon asi = new();
        asi.Clicked += AddButtonClicked;
        ser.Controls.Add(asi);


        
        
        if (ser.Controls.Length > 1) (ser.Controls[0] as ServerIcon<PublicServer>)!.LoadServer().Start();
        DrawFrame();
        MainShow += OnMainShow;
        return Task.CompletedTask;
    }
    
    protected override void OnResize(ResizeEventArgs e)
    {
        base.OnResize(e);
       
    }
    
    private Task AddButtonClicked(IRenderObject arg)
    {
        AddServerOverlay aso = new();
        aso.Clicked += AsoOnClicked;
        Controls.Add(aso);
        
        TryDraw();
        OnResize(new(CS));
        return Task.CompletedTask;
        
    }

    private Task AsoOnClicked(IRenderObject arg)
    {
        Globals.ms.Controls.Remove(arg);
        Globals.ms.DrawFrame();
        AddServerOverlay aso = (arg as AddServerOverlay)!;
        aso.Clicked -= AsoOnClicked;
        aso.Clean();
        aso = null!;
        return Task.CompletedTask;
    }

    private Task OnMainShow()
    {
        if (Globals.Luski.MainServer is not null && Globals.Luski.MainServer.IsLogedIn)
        {
            Globals.Luski.MainServer.OnError += LuskiOnOnError;
        }

        return Task.CompletedTask;
    }

    public event Func<Task>? MainShow;

    private Task LuskiOnOnError(Exception arg)
    {
        Console.WriteLine(arg);
        return Task.CompletedTask;
    }

}