using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.LogStack.Telemetry;
public sealed class TelemetryServer : IDisposable
{
    private readonly HttpListener _listener = new();
    public ConcurrentQueue<TelemetryEvent> Events { get; } = new();
    public int Count => Events.Count;
    public TelemetryServer(string prefix = "http://localhost:5155/")
    {
        _listener.Prefixes.Add(prefix);
    }
    public async Task StartAsync(CancellationToken token = default)
    {
        _listener.Start();
        while (!token.IsCancellationRequested)
        {
            var ctx = await _listener.GetContextAsync();
            _ = Task.Run(async () =>
            {
                if (ctx.Request.HttpMethod == "POST" && ctx.Request.Url?.AbsolutePath == "/telemetry")
                {
                    using var r = new StreamReader(ctx.Request.InputStream);
                    var item = JsonSerializer.Deserialize<TelemetryEvent>(await r.ReadToEndAsync());
                    if (item != null)
                    {
                        Events.Enqueue(item);
                    }
                }
                else if (ctx.Request.Url?.AbsolutePath == "/")
                {
                    var html = TelemetryDashboard.Html;
                    var bytes = System.Text.Encoding.UTF8.GetBytes(html);
                    ctx.Response.ContentType = "text/html";
                    await ctx.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
                }
                ctx.Response.Close();
            });
        }
    }
    public void Dispose() => _listener.Close();
}
