using ImGuiNET;

namespace Shoko;

class Tab
{
    ProtoHandler Handler;
    MediaHandler Document;
    public bool IsOpen = true;
    Exception Error = null;
    Stack<Uri> History;

    string txtURL = "";

    public Tab(string url)
    {
        History = new Stack<Uri>();
        Load(url);
        txtURL = url;
    }

    public void Load(string url)
    {
        Error = null;
        ImGui.SetScrollX(0);
        ImGui.SetScrollY(0);
        try
        {
            Handler = ProtoHandler.GetHandler(url);
            Handler.CurrentTab = this;
            Handler.Load();
            txtURL = Handler.URL.ToString();
            History.Push(Handler.URL);
            Document = MediaHandler.GetHandler(Handler);
            Document.Load();
        }
        catch(Exception ex)
        {
            Error = ex;
        }
    }

    public void Previous()
    {
        if(History.Count > 1)
        {
            History.Pop();
            Load(History.Pop().ToString());
        }
    }

    public void Render()
    {
        var title = txtURL;
        if(Document is not null)
        {
            title = Document.Title;
        }
        Gui.Window(title+"###"+GetHashCode().ToString(), ref IsOpen, ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.HorizontalScrollbar, ()=>
        {
            Gui.MenuBar(()=>{
                Gui.Menu("File", ()=>{
                    Gui.MenuItem("Close", null, ()=> IsOpen = false);
                });

                if(Error is null)
                {
                    Handler.MenuBar();
                    if(Handler.Loaded)
                        Document.MenuBar();
                }

                Gui.Button("<<", ()=>{
                    Previous();
                });

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

                Gui.Button("Go", ()=>{
                    Load(txtURL);
                });
                if(!Handler.Loaded && Handler.TotalBytes != 0)
                    ImGui.ProgressBar(Handler.LoadedBytes / Handler.TotalBytes);
            });
            if(Error is not null)
            {
                ImGui.Text("error: can't load page");
                ImGui.Text(Error.Message);
            }
            else
            {
                if(Handler.Loaded)
                    Document.Render();
                Handler.Render();
            }
        });
    }
}