using System;
using System.Windows;
using XplorePlane.Views;
using XplorePlane.ViewModels;
using Prism.Ioc;
using Prism.DryIoc;
using Serilog;

namespace XplorePlane
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            // 配置 Serilog 日志系统
            ConfigureLogging();

            // 捕获未处理的异常
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            DispatcherUnhandledException += OnDispatcherUnhandledException;

            base.OnStartup(e);
            
            // Initialize Prism with DryIoc
            var bootstrapper = new AppBootstrapper();
            bootstrapper.Run();
        }

        private void ConfigureLogging()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logs/xploreplane-.log", 
                    rollingInterval: RollingInterval.Day,
                    retainedFileCountLimit: 30)
                .CreateLogger();
                
            Log.Information("========================================");
            Log.Information("XplorePlane 应用程序启动");
            Log.Information("========================================");
        }

        protected override void OnExit(ExitEventArgs e)
        {
            // 关闭并刷新日志
            Log.Information("========================================");
            Log.Information("XplorePlane 应用程序退出");
            Log.Information("========================================");
            Log.CloseAndFlush();
            base.OnExit(e);
        }

        /// <summary>
        /// 处理未捕获的异常
        /// </summary>
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;
            Log.Fatal(exception, "应用程序发生未处理的异常");

            MessageBox.Show(
                $"应用程序发生严重错误：\n\n{exception?.Message}\n\n请查看日志文件获取详细信息。",
                "严重错误",
                MessageBoxButton.OK,
                MessageBoxImage.Error);
        }

        /// <summary>
        /// 处理 UI 线程未捕获的异常
        /// </summary>
        private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Log.Error(e.Exception, "UI 线程发生未处理的异常");

            MessageBox.Show(
                $"应用程序发生错误：\n\n{e.Exception.Message}\n\n请查看日志文件获取详细信息。",
                "错误",
                MessageBoxButton.OK,
                MessageBoxImage.Error);

            // 标记为已处理，防止应用程序崩溃
            e.Handled = true;
        }
    }

    public class AppBootstrapper : PrismBootstrapper
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 注册 Serilog 的 ILogger 实例
            containerRegistry.RegisterInstance<ILogger>(Log.Logger);

            // 注册 XplorePlane.Common.ILoggerService 适配器
            containerRegistry.RegisterSingleton<XplorePlane.Common.Logging.Interfaces.ILoggerService, Services.LoggerServiceAdapter>();

            // 注册视图和视图模型
            containerRegistry.RegisterForNavigation<MainWindow>();
            containerRegistry.Register<MainViewModel>();

            Log.Information("依赖注入容器配置完成");
        }
    }
}
