using System.Reflection;
using GraphicsManager;
using GraphicsManager.Interfaces;
using GraphicsManager.Objects;
using GraphicsManager.Objects.Core;
using Luski.net.Structures.Public;
using OpenTK.Windowing.Common.Input;
using Rectangle = GraphicsManager.Objects.Rectangle;

namespace Luski.GUI.MainScreen.UI.PublicServers;

public class ContentEmbed : UserControl
{
    readonly SocketFile file;
    public static Texture? t = null;
    public static Texture? DownloadIcon = null;
    long channel;
    private static bool isopen;
    public static async Task<IRenderObject> GetEmbed(ChatMessage m, SocketFile file, long channel)
    {
        
        if (file.Name.ToLower().EndsWith(".png") || file.Name.ToLower().EndsWith(".jpg"))
        {
            Stream data = await file.GetCache(CancellationToken.None);
            Texture t = Globals.ms.TextureManager.AddTexture(data);
            data.Dispose();
            Rectangle r;
            double s = 322.ScaleDouble();
            double scale = s / t.RawSize!.Value.X;
            m.Controls.Add(r = new Rectangle(t)
            {
                Size = new((int)s, (int)(scale * t.RawSize.Value.Y)),
                Shader = Texture.TextureShader[Globals.ms.Context],
                HoverMouse = MouseCursor.Hand,
                Tag = m.pc
            });
            r.Clicked += ROnClicked;
            return r;
        }
        else
        {
            ContentEmbed c;
            m.Controls.Add(c = new ContentEmbed(file, channel));
            return c;
        }
    }

    private static Task ROnClicked(IRenderObject arg)
    {
        if (isopen) return Task.CompletedTask;
        isopen = true;
        FullScreenMedia r;
        
        Globals.ms.Controls.Add(r = FullScreenMedia.GetDisplay(((Rectangle)arg).Textures[0]));
        if (arg.Tag is PublicChat pc)
        {
            pc.MessageFlow.AllowHoverFromBehind = false;
            r.Tag = pc;
        }
        
        r.Clicked += RrOnClicked;
        Globals.ms.DrawFrame();
        return Task.CompletedTask;
    }

    private static Task RrOnClicked(IRenderObject arg)
    {
        isopen = false;
        Globals.ms.Controls.Remove(arg);
        Globals.ms.DrawFrame();
        FullScreenMedia fsm = (arg as FullScreenMedia)!;
        fsm.Clicked -= RrOnClicked;
        if (fsm.Tag is PublicChat pc)
        {
            pc.MessageFlow.AllowHoverFromBehind = true;
        }
        fsm.Clean();
        fsm = null!;
        return Task.CompletedTask;
    }

    public ContentEmbed(SocketFile file, long channel)
    {
        Label fileNameLabel, fileSizeLabel;
        this.channel = channel;
        this.file = file;
        string fst = "";
        ulong size = (ulong)file.Size;
        if (size < 1000)
            fst = size + " bytes";
        else if (size < 1000000)
            fst = Math.Round(size / (double)1000, 2) + " KB";
        else if (size < 1000000000)
            fst = Math.Round(size / (double)1000000, 2) + " MB";
        else if (size < 1000000000000) fst = Math.Round(size / (double)1000000000, 2) + " GB";
        base.Size = new(333, 66);
        BackgroundColor = new(40, 40, 40, 255);
        Controls.Add(fileSizeLabel = new Label(Globals.DefaultFont) { Text = fst, Location = new(64, 39, 0) });
        Controls.Add(fileNameLabel = new Label(Globals.DefaultFont)
        {
            Color = new(102 / (float)255, 227 / (float)255, 170 / (float)255, 1), Text = file.Name,
            Location = new(64, 6, 0)
        });
        fileNameLabel.Clicked += FileNameLabelOnClicked;
        if (DownloadIcon is null)
        {
            Stream tempp =
                Tools.GetResourceStream(Assembly.GetExecutingAssembly(), "Luski.Resources.Textures.Download.png");
            DownloadIcon = Globals.ms.TextureManager.AddTexture(tempp);
            tempp.Dispose();
        }

        Controls.Add(new Rectangle(DownloadIcon)
            { Location = new(8, 6, 0), Size = new(50, 50) });
        int temp = fileNameLabel.Size.X + fileNameLabel.Location.X;
        int temp2 = fileSizeLabel.Size.X + fileSizeLabel.Location.X;
        //if (temp >= temp2) Size = new(temp + 4, Size.Y);
        //else Size = new(temp2 + 4, Size.Y);
    }

    private Task FileNameLabelOnClicked(IRenderObject arg)
    {
        string dir = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Downloads", "LuskiDownloads");
        if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
        //Thread t = new(() => file.DownloadBytes(Path.Join(dir, file.Name), channel, CancellationToken.None));
        //t.Start();
        return Task.CompletedTask;
    }
}