using System.Text;
using ImGuiNET;

namespace Shoko;

[Protocol("gemini")]
class GeminiProtoHandler : ProtoHandler
{
    string txtQuery = "";
    public GeminiProtoHandler(Uri url)
    {
        URL = url;
    }

    public override async Task Load()
    {
        var gemini = new Gemini(URL);
        gemini.Connect();
        var header = gemini.ReadHeader();
        var meta = header.Split(" ", 2, StringSplitOptions.TrimEntries);
        Status = meta[0];

        MediaType = "text/plain";

        if(Status.StartsWith('2'))
        {
            if(meta.Length > 1)
            {
                var dict = new Dictionary<string, string>();
                var type = meta[1].Split(";", StringSplitOptions.TrimEntries).ToList();
                MediaType = type[0];

                foreach (var item in type)
                {
                    var val = item.Split("=", 2);
                    dict[val[0]] = val.Length > 1 ? val[1] : "";
                }

                MediaTypeParams = dict;
            }
            Content = await Download(gemini.sslStream);
        }
        else
        {
            byte[] content = new byte[]{};
            if(meta.Length > 1)
            {
                if(Status.StartsWith('3'))
                {
                    meta[1] = "=> "+meta[1];
                    MediaType = "text/gemini";
                }
                content = Encoding.UTF8.GetBytes(meta[1]);
            }
            Content = new MemoryStream(content);
        }
        OnLoaded();
    }

    public override void Render()
    {
        if(Status.StartsWith('1'))
        {
            ImGui.InputText("##query", ref txtQuery, 1024);

            Gui.Button("Submit", ()=>{
                var uri = new UriBuilder(URL)
                {
                    Query = txtQuery
                };
                CurrentTab.Load(uri.Uri.ToString());
            });
        }
    }
}