using Inspectron.Epson;
using Inspectron.Epson.PrintServer.ConfigurationSources;
using System.Net.Http.Json;

namespace EpsonPrintService;

public class JamesDiscoveredPrintersReceiver: IDiscoveredPrintersReceiver
{
    private readonly EpsonPrintServiceConfiguration _configuration;
    private readonly HttpClient _httpClient;

    public JamesDiscoveredPrintersReceiver(EpsonPrintServiceConfiguration configuration, HttpClient httpClient)
    {
        _configuration = configuration;
        _httpClient = httpClient;
    }

    public async Task OnPrintersDiscoveredAsync(IReadOnlyList<DiscoveredPrinter> printers)
    {
        var apiKey = _configuration.ApiKey;

        var request = new DiscoveredPrintersRequest
        {
            Printers = printers.Select(p => new DiscoveredPrinterDto
            {
                PrinterId = p.IPAddress,
                Name = p.IPAddress,
                Address = p.IPAddress,
                Model = p.ModelName,
                IsMain = false
            }).ToList()
        };

        var url = $"{_configuration.ApiUrl?.TrimEnd('/')}/api/printerServer/discovered-printers";
        using var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
        requestMessage.Headers.Add("X-Printer-Server-Key", apiKey);
        requestMessage.Content = JsonContent.Create(request);

        var response = await _httpClient.SendAsync(requestMessage);
        response.EnsureSuccessStatusCode();
    }

    private class DiscoveredPrintersRequest
    {
        public List<DiscoveredPrinterDto> Printers { get; set; } = new();
    }

    private class DiscoveredPrinterDto
    {
        public string PrinterId { get; set; } = "";
        public string Name { get; set; } = "";
        public string Address { get; set; } = "";
        public string Model { get; set; } = "";
        public bool IsMain { get; set; }
    }
}