using System.Reflection;
using GraphicsManager;
using GraphicsManager.Interfaces;
using GraphicsManager.Objects;
using GraphicsManager.Objects.Core;
using Luski.net;
using OpenTK.Graphics.OpenGL4;

namespace Luski.GUI.MainScreen.UI;

public class ServerIcon<TServer> : UserControl where TServer : Server
{
    private Rectangle SelectedRect;
    private static ServerIcon<MainServer>? ser1;
    private static ServerIcon<PublicServer>? ser2;
    private bool Selected = false;
    
    public async Task LoadServer()
    {
        Selected = true;
        if (ser1 is not null)
        {
            ser1.SelectedRect.BackgroundColor = new(26, 26, 26, 255);
            ser1.Selected = false;
            ser1 = null;
        }
        if (ser2 is not null)
        {
            ser2.SelectedRect.BackgroundColor = new(26, 26, 26, 255);
            ser2.Selected = false;
            ser2 = null;
        }

        SelectedRect.BackgroundColor = new(255, 255, 255, 255);
        Globals.UserTextureMap.Clear();
        if (typeof(TServer).FullName == typeof(PublicServer).FullName)
        {
            ser2 = this as ServerIcon<PublicServer>;
            await Globals.ms.LoadPublicServer(ser2!.Server);
        }
        else
        {
            ser1 = this as ServerIcon<MainServer>;
            await Globals.ms.LoadMainServer(ser1!.Server);
        }
    }
    
    public ServerIcon(TServer Server)
    {
        Rectangle r = new(Globals.ms.TextureManager.GetTextureResource("rc.png"))
        {
            Location = new(18.ScaleInt(), 8.ScaleInt(), 0),
            Size = new(32.ScaleInt()),
            Shader = Rectangle.DefaultAlphaTextureShader[Globals.ms.Context],
            IgnoreHover = true
        };
        Rectangle rr = new(r.Textures[0])
        {
            Location = new(17.ScaleInt(), 7.ScaleInt(), 0),
            Size = new(34.ScaleInt()),
            Shader = Rectangle.DefaultAlphaShader[Globals.ms.Context],
            BackgroundColor = new(26, 26, 26, 255),
            IgnoreHover = true
        };
        SelectedRect = new(r.Textures[0])
        {
            Location = new(14.ScaleInt(), 4.ScaleInt(), 0),
            Size = new(40.ScaleInt()),
            Shader = Rectangle.DefaultAlphaShader[Globals.ms.Context],
            BackgroundColor = new(26, 26, 26, 255),
            IgnoreHover = true
        };
        this.Server = Server;
        Texture t = Globals.ms.TextureManager.AddTexture(Server.GetAvatar(CancellationToken.None).Result);
        t.Unit = TextureUnit.Texture1;
        r.Textures.Add(t);
        Controls.Add(SelectedRect);
        Controls.Add(rr);
        Controls.Add(r);
        base.BackgroundColor = new(26, 26, 26, 255);
        this.Clicked += OnClicked;
        base.Size = new(68.ScaleInt(), 48.ScaleInt());
    }
    
    private async Task OnClicked(IRenderObject arg)
    {
        if (Selected) return;
        await LoadServer();
    }

    public TServer Server { get; }
}