using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using System.Net;
using System.Text;
using System.IO;

public class BrowserServer : MonoBehaviour
{

    [SerializeField]
    [Tooltip("Local Path in Streaming Assets")]
    private string LocalPath;

    [SerializeField]
    [Tooltip("Site to redirect to if android")]
    private string redirectSite;

    [SerializeField]
    [Tooltip("Browsers by default use 80")]
    private int port = 80;

    SimpleHTTPServer server;

    // Start is called before the first frame update
    void Start()
    {
        server = new SimpleHTTPServer(Path.Combine(Application.streamingAssetsPath,LocalPath),port);
    }

    private void OnDisable()
    {
        server.Stop();
    }

    private void StartServer()
    {
        if (!HttpListener.IsSupported)
        {
            Debug.LogWarning("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            return;
        }

        string responseString = "<html><body><h1>Error Connecting to server</h1></body></html>";



        // Create a listener.
        HttpListener server = new HttpListener();
        // Add the prefixes.


        server.Prefixes.Add("http://*:" + port.ToString() + "/");
        server.Start();
        Debug.Log(" HTML Listening...");

        // while (enabled)
        // {
        HttpListenerContext context = server.GetContext();
        HttpListenerResponse response = context.Response;


        string page = Path.Combine(Application.streamingAssetsPath, LocalPath, context.Request.Url.LocalPath);
        Debug.Log("Client asked for: " + context.Request.Url.LocalPath);
        if (page.EndsWith("/"))
            page += "index.html";

        Debug.Log("Client asked for: " + page);

        if (page == string.Empty)
            page = "index.html";

        try
        {
            TextReader tr = new StreamReader(page);
            string msg = tr.ReadToEnd();
            byte[] buffer = Encoding.UTF8.GetBytes(msg);

            response.ContentLength64 = buffer.Length;
            Stream st = response.OutputStream;
            st.Write(buffer, 0, buffer.Length);
        }
        catch (IOException e)
        {
            Debug.LogError(e);
        }



        context.Response.Close();
        //}

        server.Stop();
        Task.Run(() => StartServer());
    }

    private void Respond(HttpListenerContext context)
    {

        string responseString = "<html><body><h1>Error Connecting to server</h1></body></html>";
        try
        {
            responseString = System.IO.File.ReadAllText(Path.Combine(Application.streamingAssetsPath, LocalPath, context.Request.Url.LocalPath));
            Debug.Log(responseString);
        }
        catch (System.IO.IOException e)
        {
            Debug.LogError(e);
        }

        HttpListenerRequest request = context.Request;
        // Obtain a response object.
        HttpListenerResponse response = context.Response;
        // Construct a response.

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        // You must close the output stream.
        output.Close();
    }

}
