using console_opcua_sgdn_tornio.Controllers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Opc.Ua;
using Opc.Ua.Client;
using Serilog;
using System.Linq.Expressions;
using System.Reflection.PortableExecutable;
using System.Threading.Channels;
using console_opcua_sgdn_tornio.Models;
using console_opcua_sgdn_tornio.Service;

namespace console_opcua_sgdn_tornio
{
    public static class Program
    {
        static async Task Main(string[] args)//void Mian(string[] args)
        {
            try
            {
                // Add logger
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Directory.CreateDirectory("pki/own");
            Directory.CreateDirectory("pki/trusted");
            Directory.CreateDirectory("pki/issuers");
            Directory.CreateDirectory("pki/rejected");

            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config =>
                {
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                })
                //.UseSerilog(Log.Logger)
                .ConfigureServices((context, services) =>
                {
                    services.AddHostedService<QueuePolling>();
                    services.AddHostedService<MachinePolling>();

                })
                .Build()
                .Run();


            //CancellationTokenSource source = new CancellationTokenSource();
            //CancellationToken ct = source.Token;

            //var opc = new OpcUaConnection(ct);

            //Console.WriteLine("Connessione al server OPC UA...");
            //await opc.ConnectAsync("opc.tcp://10.2.5.1:4840");


            //var reader = new OpcUaReader(opc.Session);

            //var ctx = new OperationContext();

            //while (!ct.IsCancellationRequested)
            //{
            //    if (!opc.Session.Connected)
            //        source.Cancel();

            //    try
            //    {
            //        OpcUaOperation.Browse(opc.Session, new NodeId(100000, 2));
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine("Errore durante la lettura OPC UA: " + ex.Message);
            //    }
            //}

            //bool programRunning = await reader.ReadBool(HeidenhainNodes.ProgramRunning);
            //bool spindleOn = await  reader.ReadBool(HeidenhainNodes.SpindleOn);
            //bool ncError = await  reader.ReadBool(HeidenhainNodes.NcError);

            //stateMachine.Update(
            //    ctx,
            //    programRunning,
            //    spindleOn,
            //    ncError,
            //    opId);

            //await Task.Delay(200, ct);

            //// Read esempio
            //var value = await opc.ReadNodeAsync("ns=2;s=Demo.Static.Scalar.Double");
            //Console.WriteLine("Valore letto: " + value.Value);

            //// Write esempio
            //// await opc.WriteNodeAsync("ns=2;s=Demo.Static.Scalar.Double", 123.45);

            //// Subscription esempio
            //var sub = opc.CreateSubscription(1000);
            //var item = new MonitoredItem(sub.DefaultItem)
            //{
            //    StartNodeId = "ns=2;s=Demo.Static.Scalar.Double",
            //    SamplingInterval = 1000
            //};
            //item.Notification += (m, args) =>
            //{
            //    var v = ((MonitoredItemNotification)args.NotificationValue).Value;
            //    Console.WriteLine("Cambio: " + v.Value);
            //};
            //sub.AddItem(item);
            //sub.ApplyChanges();

            //Console.WriteLine("Premi invio per uscire...");
            //Console.ReadLine();

            //opc.Disconnect();
        }
    }
}