using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace VIZ.Framework.Module
{
    /// <summary>
    /// 应用程序启动 -- 捕获未处理异常
    /// </summary>
    public class AppSetup_CatchUnhandledException : AppSetupBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(AppSetup_CatchUnhandledException));

        /// <summary>
        /// 描述
        /// </summary>
        public override string Detail { get; } = "应用程序启动 -- 捕获未处理异常";

        /// <summary>
        /// 执行启动
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        /// <returns>是否成功执行</returns>
        public override bool Setup(AppSetupContext context)
        {
            Application.Current.DispatcherUnhandledException -= App_DispatcherUnhandledException;
            Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;

            AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            return true;
        }

        /// <summary>
        /// 执行关闭
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        public override void Shutdown(AppSetupContext context)
        {

        }

        /// <summary>
        /// 应用程序未处理异常
        /// </summary>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Debug.WriteLine(e.ExceptionObject);
            log.Error(e.ExceptionObject);
        }

        /// <summary>
        /// WPF应用程序未处理异常
        /// </summary>
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Debug.WriteLine(e.Exception.Message);
            log.Error(e.Exception);
        }
    }
}
