using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Xml;
using ComPDFKit.NativeMethod;
using Compdfkit_Tools.Helper;

namespace PDFViewer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App: Application
    {
        static public bool DefaultPDFLoaded = false;
        public static List<string> OpenedFilePathList = new List<string>();

        public App()
        {
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }


        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            var ex = e.Exception as Exception;
            if (ex != null)
            {
                MessageBox.Show("发生Task未处理异常:" + ex.Message + "\n" + ex.StackTrace, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                Exception ex = (System.Exception)e.ExceptionObject;
                MessageBox.Show("发生非UI线程异常:" + ex.Message + "\n" + ex.StackTrace, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            MessageBox.Show("发生UI线程异常:" + e.Exception.Message + "\n" + e.Exception.StackTrace, "系统错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            string str = this.GetType().Assembly.Location;
            base.OnStartup(e);
            LicenseVerify();
        }
        
        private static bool LicenseVerify()
        {
            bool result = false;

            result = CPDFSDKVerifier.LoadNativeLibrary();
            if (!result)
                return false;
            SDKLicenseHelper sdkLicenseHelper = new SDKLicenseHelper();

            LicenseErrorCode verifyResult = CPDFSDKVerifier.LicenseVerify(sdkLicenseHelper.key, sdkLicenseHelper.secret);
            if (verifyResult != LicenseErrorCode.LICENSE_ERR_SUCCESS)
                return false;
            return result;
        }
    }
}
