using Inspectron.Epson;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;
using Ninject;
using System.Threading.Channels;
using Inspectron.Epson.PrintServer;
using Inspectron.Epson.PrintServer.ConfigurationSources;
using Inspectron.Epson.PrintServer.JobSources;
using Inspectron.Epson.PrintServer.PrinterAssinment;
using Inspectron.Epson.PrintServer.Printers;
using Inspectron.Epson.PrintServer.Printers.Utils;
using Inspectron.Epson.PrintServer.PrintServices;
using EpsonPrintService;
using Inspectron.Epson.Queue;

StandardKernel kernel = new StandardKernel();


var configPath = ConfigurationPaths.GetConfigPath();
Console.WriteLine($"Loading configuration from: {configPath}");

var base64Line = File.ReadAllText(configPath).Trim();
var decodedConfig = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(base64Line));
var configParts = decodedConfig.Split(';');
if (configParts.Length != 3)
    throw new InvalidOperationException($"Invalid configuration format. Expected 'apiUrl;restaurantId;apiKey', got {configParts.Length} parts.");

var config = new EpsonPrintServiceConfiguration
{
    ApiUrl = configParts[0],
    RestaurantId = configParts[1],
    ApiKey = configParts[2]
};

Console.WriteLine($"Restaurant: {config.RestaurantId}");
Console.WriteLine($"API URL: {config.ApiUrl}");

//kernel.Bind<IDiscoveryService>().To<DiscoveryService>().InSingletonScope();

var discovery = new PreconfiguredDiscoveryService();
discovery.AddPrinter("192.168.50.176", "TM-T30III", port: 9100);
discovery.AddPrinter("192.168.50.60", "TM-T30III", port: 9100);
discovery.AddPrinter("192.168.50.61", "TM-T30III", port: 9100);
discovery.AddPrinter("192.168.50.80", "TM-U220II", port: 9100);
kernel.Bind<IDiscoveryService>().ToConstant(discovery);

kernel.Bind<HttpClient>().ToConstant(new HttpClient { Timeout = TimeSpan.FromSeconds(30) }).InSingletonScope();


kernel.Bind<EpsonPrintServiceConfiguration>().ToConstant(config);
//kernel.Bind<IPrinterFactory>().ToMethod(sp=>new HtmlPrinterFactory("TM-U220II.html", paperWidth: 258,type:0x0d, logger:sp.Kernel.Get<ILogger>()));
//kernel.Bind<IPrinterFactory>().ToMethod(sp=>new HtmlPrinterFactory("TM-T30III.html",logger:sp.Kernel.Get<ILogger>()));
kernel.Bind<IPrinterFactory>().To<EpsonPrinterFactory>();

kernel.Bind<IPrintJobSource, SignalRPrintJobSource>().To<SignalRPrintJobSource>().InSingletonScope();
kernel.Bind<IPrintService>().To<Inspectron.Epson.PrintServer.PrintServices.EpsonPrintService>();
kernel.Bind<ILogger>().ToMethod(ctx =>
{
    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole();
        builder.SetMinimumLevel(LogLevel.Trace);
    });
    return loggerFactory.CreateLogger("EpsonPrintService");
});

kernel.Bind<IWrapperPrinterFactory>().To<PrinterWrapperFactory>().InSingletonScope();
kernel.Bind<IPrinterConfigurationSource>().To<FixedConfigurationSource>();
kernel.Bind<IReceiptConverterFactory>().To<ReceiptConverterFactory>().InSingletonScope();
kernel.Bind<IJobStatusReporter>().To<NullJobStatusReporter>();
kernel.Bind<PrintServer>().ToSelf().InSingletonScope();
kernel.Bind<IDiscoveredPrintersReceiver>().To<JamesDiscoveredPrintersReceiver>().InSingletonScope();
kernel.Bind<PrinterDiscoveryBackgroundTask>().ToSelf().InSingletonScope();
kernel.Bind<HeartbeatBackgroundTask>().ToSelf().InSingletonScope();

var printLoop = kernel.Get<PrintLoop>();
var printServer = kernel.Get<PrintServer>();


 
var discoveryTask = kernel.Get<PrinterDiscoveryBackgroundTask>();
var heartbeatTask = kernel.Get<HeartbeatBackgroundTask>();

//printServer.RegisterPrinter("10.0.20.12");


await printLoop.StartAsync();


var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
    Console.WriteLine("\nShutting down...");
    e.Cancel = true;
    cts.Cancel();
};

// Start background tasks
_ = discoveryTask.StartAsync(cts.Token);
_ = heartbeatTask.StartAsync(cts.Token);

try
{
    await Task.Delay(Timeout.Infinite, cts.Token);
}
catch (TaskCanceledException)
{
    // Expected when Ctrl+C is pressed
}

