using System.Text;
using System.Web;
using HeyRed.Mime;
using Microsoft.Win32.SafeHandles;

namespace Shoko;

[Protocol("file")]
class FileProtoHandler : ProtoHandler
{
    public FileProtoHandler(Uri url)
    {
        URL = url;
    }
    long _totalBytes = -1;
    public override long TotalBytes => _totalBytes;

    public override async Task Load()
    {
        var file = HttpUtility.UrlDecode(URL.AbsolutePath);

        if(URL.Host.Length > 0)
            file = "//" + URL.Host + file;

        MediaType = "text/plain";
        Status = "OK";

        if(File.Exists(file))
        {
            var fi = new FileInfo(file);
            _totalBytes = fi.Length;
            var stream = fi.OpenRead();
            Content = await Download(stream);
            MediaType = MimeGuesser.GuessMimeType(Content);
        }
        else if(Directory.Exists(file))
        {
            MediaType = "text/gemini";
            var str = "# "+file+"\r\n";
            var entries = Directory.EnumerateFileSystemEntries(file);

            foreach(var entry in entries)
            {
                var path = Path.GetFileName(entry);
                str += string.Format("=>{0}/{1} {2}\r\n", URL.ToString(), HttpUtility.UrlEncode(path), path);
            }

            Content = new MemoryStream(Encoding.UTF8.GetBytes(str));
        }
        else
        {
            Content = new MemoryStream(Encoding.UTF8.GetBytes("file not found"));
            Status = "not found";
        }
        OnLoaded();
    }
    public override void Render()
    {
    }
}