using System;
using System.Collections.Generic;
using System.IO;
using MrWu;
using MrWu.Debug;
using Server.Core;
using WebSocketSharp.Net;
using WebSocketSharp.Server;

namespace Server.Net
{
    public class HttpNetManager<T> : SingleInstance<T>,IDisposable where T : SingleInstance,new()
    {
        protected HttpServer _httpServer;
        
        public virtual void Start(int port,string docPath = null)
        {
            if (_httpServer != null)
            {
                Debug.Warning("HttpServer is not null!");
                return;
            }
            
            _httpServer = new HttpServer($"http://0.0.0.0:{port}");
            if (!string.IsNullOrEmpty(docPath))
            {
                _httpServer.DocumentRootPath = docPath;
            }

            _httpServer.OnPost += OnPost;
            _httpServer.OnGet += OnGet;
            _httpServer.Start();
        }

        protected virtual void OnGet(object sender,HttpRequestEventArgs args)
        {
            Debug.Log("OnGet---");
            var res = args.Response;

            res.StatusCode = (int)HttpStatusCode.NotModified;
        }

        protected virtual void OnPost(object sender, HttpRequestEventArgs args)
        {
            Debug.Log("OnPost---");
            var res = args.Response;
            
            res.StatusCode = (int)HttpStatusCode.NotModified;
        }

        public virtual void Dispose()
        {
            _httpServer.Stop();
        }

        protected string ReadRequest(HttpListenerRequest request)
        {
            using (StreamReader streamReader = new StreamReader(request.InputStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}