using Khd.Core.EntityFramework;
using Khd.Core.Library;
using Khd.Core.Wcs;
using Khd.Core.Wcs.Global;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Diagnostics;

internal class Program
{
    private static LoggerUtils _logger = new LoggerUtils();
    private static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "Main";
        Console.ForegroundColor = ConsoleColor.Yellow;
        Init(); //初始化加载配置文件
        AppDomain.CurrentDomain.UnhandledException += GlobalExceptionHandler; //全局异常捕获
        try
        {
            Process[] processes = Process.GetProcessesByName("Khd.Core.Wcs");
            if (processes.Length > 1)
            {
                Console.Write("系统已经启动,请勿重复启动1");
                Console.ReadLine();
                return;
            }
            var mutex = new Mutex(true, "Khd.Core.Wcs", out bool ret);
            if (ret)
            {
                IHost host = CreateHostBuilder(args).Build();

                _logger.Info("系统启动开始");
                Console.WriteLine($"{DateTime.Now}:系统启动开始");

                MainCentralControl main = new(host);
                main.Start();
                mutex.ReleaseMutex(); // 释放 Mutex

                _logger.Info("系统启动成功");
                Console.WriteLine($"{DateTime.Now}:系统启动成功");

                while (true)
                {
                    Console.ReadLine();
                }
            }
            else
            {
                Console.Write("系统重复开启,请先关闭之前窗口");
                Console.ReadLine();
            }
        }
        catch (Exception ex)
        {
            Console.Write("系统启动异常:" + ex.Message + "\n" + ex.StackTrace);
            _logger.Error(ex.Message + "\n" + ex.StackTrace);
        }

    }
    private static void GlobalExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        //当前线程名称
        Thread.CurrentThread.Name = "Error";
        if (e.ExceptionObject is Exception exception)
        {
            Console.WriteLine("全局异常捕获:");
            Console.WriteLine(exception.Message);
            Console.WriteLine(exception.StackTrace);
            _logger.Info("全局异常捕获:" + exception.Message + "\n" + exception.StackTrace);
        }
        else
        {
            Console.WriteLine("未知异常捕获:");
            Console.WriteLine(e.ExceptionObject);
            _logger.Info("未知异常捕获:" + e.ExceptionObject);
        }
    }

    /// <summary>
    /// 初始化加载配置文件
    /// </summary>
    private static void Init()
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
               .AddJsonFile("appsettings.json")
               .Build();

        StaticData.PlcConfigs = configuration.GetSection("PlcConfigs").Get<List<PlcConfig>>();
        ConnectionStrings.ConnectionString = configuration["ConnectionStrings:DefaultConnection"];
        StaticData.DeleteLogDay = Convert.ToInt32(configuration["DeleteLogDays"] ?? "10");
    }
    private static IHostBuilder CreateHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)
           .ConfigureServices((_, services) =>
           {
               services.AddDbContext<DefaultDbContext>(options =>
                   options.UseMySql(ConnectionStrings.ConnectionString, new MySqlServerVersion(new Version(8, 0, 31))), ServiceLifetime.Transient);
           });
}
