using System.Net;

namespace Tesses.Http.KitchenSink;

class AspRouteStyle : ASPEndpointRequestHandler
{
    [HttpGet]
    public string Add(int a,int b)
    {
        return $"{a} + {b} = {a+b}";
    }
    [HttpGet]
    public object Something(bool b,int i,double f,string sz)
    {
        return new {
            Boolean = b,
            Integer = i,
            Double=f,
            String=sz


        };
    }
}

class Program
{
    public static async Task Main(string[] args)
    {
       
        MountableServer mountableServer=new MountableServer(RequestHandler.FromDirectory("WebSite"));
        mountableServer.Mount("/SrcDl",RequestHandler.FromDelegateSync(e=>{
            e.Response.SendFileAsDownload("Program.cs");
        }));
        mountableServer.Mount("/PasswordProtected",new BasicAuthRequestHandler((user,pass)=>{return user=="ddlovato" && pass=="somepassword";},RequestHandler.FromDelegateSync(e=>{
            e.Response.WithContentType("text/plain").SendText("Password Protected Data");
        })));
        mountableServer.Mount("/4d",RequestHandler.FromDelegateSync(e=>{
             HTTPClient client = HTTPClient.Open("GET","https://nextcloud.tesses.cf/apps/files_sharing/publicpreview/aYHgTAxNcAXNG3R?x=2258&y=727&a=true&file=celluloid-shot1007.jpg&scalingup=0");
             client.SendToServer(e);
        }));
        mountableServer.Mount("/Endpoints/ASP",new AspRouteStyle());
        mountableServer.Mount("/Endpoints/upload_data/",
            RequestHandler.FromDelegateSync(e=>{
                
                var parser=e.Request.GetMultipartParser();
                
                parser.Parse((a,b,c)=>{
                    
                    return File.Create(Path.Combine("WebSite","Endpoints","uploads",b));
                },true).ToArray();
                e.Response.WithContentType("text/plain").SendText("HELLO");
            })
        );
        SendEvents evts=new SendEvents();
        mountableServer.Mount("/counter/count",RequestHandler.FromDelegateSync(e=>{
            
            e.Response.ServerSentEvents(evts);
            

        }));

        Thread t=new Thread(()=>{
            for(long i =0;;i++){
            evts.SendEvent($"Ran for {i} Seconds");
            Thread.Sleep(1000);
            }
        });
        t.Start();

        HTTPServer server=new HTTPServer(mountableServer,new System.Net.Sockets.TcpListener(new IPEndPoint(0,3333)));
        server.AllowMultipleRequestsOnOneConnection=true;
        await server.ListenAsync();
    }
}