using System.Reflection;
using System.Runtime.InteropServices;
using CFX;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Sln.Iot.Business;
using Sln.Iot.CFX;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
using Sln.Iot.Common;
using Sln.Iot.Config;
using Sln.Iot.PLC;
using Sln.Iot.Repository;
using Sln.Iot.Serilog;
using TouchSocket.Sockets;

namespace Sln.Iot
{
    /// <summary>
    /// 程序主入口
    /// </summary>
    public class Program
    {
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);

        public static bool HandlerRoutine(int CtrlType)
        {
            try
            {
                switch (CtrlType)
                {
                    case 0:
                        ProgramClose();
                        break;
                    case 2:
                        ProgramClose();
                        break;
                }
            }
            catch (Exception ex)
            {
                SerilogHelper.Instance.Error("程序退出事件异常", ex);
            }
            finally
            {
                SerilogHelper.Instance.Info("系统关闭");
            }
            
            return false;
        }

        static async Task Main(string[] args)
        {
            bool isNotRunning;  //互斥体判断
            System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out isNotRunning);   //同步基元变量
            if (!isNotRunning)  // 如果不是未运行状态
            {
                Environment.Exit(1);
            }

            SetConsoleCtrlHandler(cancelHandler, true);
            //Serilog中间件
            SerilogExtensions.UseSerilogExtensions();
            //日志实例
            var log = SerilogHelper.Instance;
            //配置文件加载
            var appConfig = AppConfigSetting.Load();
            //PLC连接初始化
            PLCConnect.Instance.InitConnect();
            GlobalVar.OpenTime = DateTime.Now;

            //CFX接口启动
            //真空注胶机
            CFXConnectOven.Instance.Init(appConfig.VacuumConfig.CFXHandle,
                new Uri(appConfig.VacuumConfig.LocalURI),
                new Uri(appConfig.VacuumConfig.UpperURI));
            //提升机1
            CFXConnectVacuum.Instance.Init(appConfig.OvenConfig.CFXHandle,
                new Uri(appConfig.OvenConfig.LocalURI),
                new Uri(appConfig.OvenConfig.UpperURI));

            TouchTcpServer.Instance.TcpServerStarted(appConfig.TcpServerConfig);

            //业务类启动
            BusinessStart business = new BusinessStart();

            log.Info($"系统启动成功,日志存放位置:{Environment.CurrentDirectory}");

            //CFXTest cFXTest = new CFXTest();
            //cFXTest.Test1();

            //TestBusiness test = new TestBusiness();

            await Task.Delay(-1);
        }

        /// <summary>
        /// 程序退出事件
        /// </summary>
        public static void ProgramClose()
        {
            CFXConnectOven.Instance.PublishEvent(new CFXEnvelope(new EndpointShuttingDownEvent().Handle(CFXConnectOven.Instance.CFXHandle)));
            CFXConnectVacuum.Instance.PublishEvent(new CFXEnvelope(new EndpointShuttingDownEvent().Handle(CFXConnectVacuum.Instance.CFXHandle)));
        }
    }
}