using ASTM_D7896_Tester.Models;
using ASTM_D7896_Tester.Services;
using ASTM_D7896_Tester.Views;
using Microsoft.Extensions.Configuration;
using OfficeOpenXml;
using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;

namespace ASTM_D7896_Tester
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static IPlcService PlcService { get; private set; }
        public static AppConfig PlcConfig { get; private set; }
        protected override async void OnStartup(StartupEventArgs e)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            base.OnStartup(e);

            // 防止在登录窗口关闭时应用程序因没有窗口而自动退出
            ShutdownMode = ShutdownMode.OnExplicitShutdown;






            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var configuration = builder.Build();

            // appsettings.json in this project keeps PLC settings at the root of the file
            // (not under a "PlcSettings" section). Bind the entire configuration to AppConfig.
            PlcConfig = configuration.Get<AppConfig>() ?? new AppConfig();

            PlcService = new PlcService(PlcConfig);

            var plcService = App.PlcService as PlcService;
            try
            {
                await plcService.EnsureConnectedAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"PLC 连接失败：{ex.Message}");
            }

            // 启动主窗口，设置为应用程序的主窗口并恢复默认的退出模式
            var mainWindow = new MainWindow();
            MainWindow = mainWindow;
            ShutdownMode = ShutdownMode.OnMainWindowClose;
            mainWindow.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            (PlcService as IDisposable)?.Dispose();
            base.OnExit(e);
        }
    }

}
