using System.Text;

namespace Shoko;

[Protocol("data")]
class DataProtoHandler : ProtoHandler
{
    public DataProtoHandler(Uri url)
    {
        URL = url;
    }

    public override Task Load()
    {
        var data = new UriBuilder(URL).Path;

        var parts = data.Split(",");
        var type = parts[0].Split(";", StringSplitOptions.TrimEntries).ToList();
        var dict = new Dictionary<string, string>();
        MediaType = type.Count > 0 && type[0].Length > 0 ? type[0] : "text/plain";
        type.RemoveAt(0);

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

        if(dict.ContainsKey("base64"))
        {
            Content = new MemoryStream(Convert.FromBase64String(parts[1]));
        }
        else
        {
            Content = new MemoryStream(Encoding.UTF8.GetBytes(parts[1]));
        }

        MediaTypeParams = dict;
        Status = "OK";
        OnLoaded();
        return Task.CompletedTask;
    }
    public override void Render()
    {
    }
}