using System.Reflection;
using ImGuiNET;

namespace Shoko;

static class MainUI
{
    static string txtURL = "";

    public static List<Tab> tabs = new List<Tab>();

    public static ImFontPtr Font;
    public static List<ImFontPtr> HeadingFonts = new List<ImFontPtr>();
    public static ImFontPtr MonospaceFont;

    public static void NewTab(string url)
    {
        tabs.Add(new Tab(url));
    }

    public static unsafe void AddFontFromResource(string resource, Action<IntPtr, int> f)
    {
        using(var m = new MemoryStream())
        {
            Assembly.GetExecutingAssembly().GetManifestResourceStream(resource).CopyTo(m);
            var fontBuffer = m.ToArray();
            fixed(byte* buffer = fontBuffer)
            {
                f(new IntPtr(buffer), fontBuffer.Length);
            }
        }
    }

    public static bool Load(string[] args)
    {
        var io = ImGui.GetIO();
        ImGui.StyleColorsDark();
        io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;

        AddFontFromResource("RobotoFlex.ttf", (buf, len)=>{
            Font = io.Fonts.AddFontFromMemoryTTF(buf, len, 16f);
            HeadingFonts.Add(io.Fonts.AddFontFromMemoryTTF(buf, len, 32f));
            HeadingFonts.Add(io.Fonts.AddFontFromMemoryTTF(buf, len, 24f));
            HeadingFonts.Add(io.Fonts.AddFontFromMemoryTTF(buf, len, 20f));
        });
        AddFontFromResource("RobotoMono.ttf", (buf, len)=>{
            MonospaceFont = io.Fonts.AddFontFromMemoryTTF(buf, len, 16f);
        });

        if(args.Length > 0)
            foreach (var arg in args)
                NewTab(arg);

        return true;
    }

    public static bool Render()
    {
        bool quit = true;

        ImGui.PushFont(Font);

        ImGui.DockSpaceOverViewport();

        Gui.MainMenuBar(()=>
        {
            Gui.Menu("File", ()=>
            {
                Gui.MenuItem("Quit", null, ()=> quit = false);
            });
            Gui.Menu("Help", ()=>
            {
                Gui.MenuItem("About", null, ()=> NewTab("about:"));
            });

            ImGui.InputText("##url", ref txtURL, 1024);

            Gui.Button("Go", ()=>{
                NewTab(txtURL);
                txtURL = "";
            });
        });

        tabs = tabs.Where(x=>x.IsOpen).ToList();

        foreach (var tab in tabs)
        {
            tab.Render();
        }

        ImGui.PopFont();

        return quit;
    }
}