using System;
using System.Threading.Tasks;
using MDP.SID.Scripting.Grpc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Text;
        
private HttpListener _listener;
private const string Url = "http://localhost:8000/";
private string _userImagesPath;
private string _scriptFilesPath;
private string _lastGrantedEvent = "";
private string _lastGrantedImagePath = "";
private int _lastUserId = 0;

private async void EventReceived(Event received)
{
  if (received.LocalizedTypeName == "Access granted")
  {
	  _lastGrantedEvent = $"{received.LocalizedTypeName} {received.FirstName} {received.LastName} {received.Time.ToDateTimeOffset()}";
	  var userImage = await Context.GetUserDefaultImageAsync((int)received.UserId);
	  _lastGrantedImagePath = userImage.Image;
	  _lastUserId = (int)received.UserId;
  }
}

public async Task HandleIncomingConnections(CancellationToken stoppingToken)     
{
	var runServer = true; 

	while (!stoppingToken.IsCancellationRequested && runServer)
	{
		var ctx = await _listener.GetContextAsync();
		var req = ctx.Request;
		var resp = ctx.Response;
		if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/shutdown"))
		{
			runServer = false;
		}
		else if ((req.HttpMethod == "GET") && (req.Url.AbsolutePath == "/doors"))
		{
			await WriteResponseAsync(resp, "application/json", JsonConvert.SerializeObject(new { Name = _lastGrantedEvent, Path = _lastGrantedImagePath}));
			continue;
		}
		else if ((req.HttpMethod == "GET") && (req.Url.AbsolutePath == "/doors2"))
		{
			var doors = await Context.GetDoorsAsync();
			await WriteResponseAsync(resp, "application/json", JsonConvert.SerializeObject(doors));
			continue;
		}
		else if (req.HttpMethod == "GET" && req.Url.AbsolutePath.Contains("Jpeg"))
		{
			await using var fsSource = new FileStream(Path.Combine(_userImagesPath, _lastUserId.ToString(), _lastGrantedImagePath), FileMode.Open);
			var bytes = new byte[fsSource.Length];
			var numBytesToRead = (int)fsSource.Length;
			var numBytesRead = 0;

			while (numBytesToRead > 0)
			{
				var n = await fsSource.ReadAsync(bytes, numBytesRead, numBytesToRead, stoppingToken);
				if (n == 0) break;
				numBytesRead += n;
				numBytesToRead -= n;
			}

			numBytesToRead = bytes.Length;

			await using (var hsSource = resp.OutputStream)      
			{
				await hsSource.WriteAsync(bytes, 0, numBytesToRead, stoppingToken);
			}

			continue;
		}
    
		var index = File.ReadAllText(Path.Combine(_scriptFilesPath, "index.html"));

		await WriteResponseAsync(resp, "text/html", index);
	}
}

private static async Task WriteResponseAsync(HttpListenerResponse response, string contentType, string content)
{
	response.ContentType = contentType;
	response.ContentEncoding = Encoding.UTF8;
	var bytes = Encoding.UTF8.GetBytes(content);
	response.ContentLength64 = bytes.LongLength;
	await using var hsSource = response.OutputStream;
	await hsSource.WriteAsync(bytes, 0, bytes.Length);   
} 

_userImagesPath = await Context.GetUserImagesPathAsync();

_scriptFilesPath = await Context.GetScriptFilesPathAsync();

Context.LogInformation(_scriptFilesPath);

Context.OnEventReceived += EventReceived;

_listener = new HttpListener();

_listener.Prefixes.Add(Url);
_listener.Start();

Context.LogInformation($"Listening for connections on {Url}");

await HandleIncomingConnections(CancellationToken);

_listener.Close();

Context.LogInformation("Script done");