using System.Numerics;
using ImGuiNET;

namespace Shoko;

[MediaType("text/gemini")]
class GeminiMediaHandler : MediaHandler
{
    List<string> lines;
    public GeminiMediaHandler(ProtoHandler content)
    {
        Content = content;
        lines = new List<string>();
    }

    public override void Load()
    {
        Title = new UriBuilder(Content.URL).Path;
        var reader = new StreamReader(Content.Content);
        string line;
        while((line = reader.ReadLine()) is not null)
        {
            lines.Add(line);
        }
    }

    public override void Render()
    {
        var formatting = true;
        foreach(var line in lines)
        {
            if(line.StartsWith("```"))
            {
                formatting = !formatting;
                if(formatting) ImGui.PopFont();
                else ImGui.PushFont(MainUI.MonospaceFont);
            }
            else if(formatting)
            {
                if(line.StartsWith("=>"))
                {
                    var parts = line[2..].Trim().Split(new char[]{' ', '\t'}, 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
                    var title = parts[parts.Length > 1 ? 1 : 0];
                    var linkurl = new Uri(Content.URL, parts[0]).ToString();
                    ImGui.TextColored(new Vector4(0,0,255,255), title.Trim());
                    ImGui.SetItemTooltip(linkurl);
                    if(ImGui.IsItemClicked(ImGuiMouseButton.Left))
                        Content.CurrentTab.Load(linkurl);
                }
                else if(line.StartsWith("#"))
                {
                    var heading = 1;
                    if(line.StartsWith("##")) heading = 2;
                    if(line.StartsWith("###")) heading = 3;

                    ImGui.PushFont(MainUI.HeadingFonts[heading-1]);

                    ImGui.TextUnformatted(line[heading..].Trim());

                    ImGui.PopFont();
                }
                else if(line.StartsWith("* "))
                {
                    ImGui.BulletText(line[2..].Trim());
                }
                else if(line.StartsWith(">"))
                {
                    ImGui.TextDisabled("    "+line.Trim());
                }
                else
                    ImGui.TextWrapped(line.Trim());
            }
            else
                ImGui.TextUnformatted(line);
        }
        if(!formatting) ImGui.PopFont();
    }
}