using System;
using System.Globalization;
using System.IO;
using System.Windows;
using Microsoft.Win32;

namespace WPF_ScanControl_Sample
{
    /// <summary>
    /// App.xaml 的互動邏輯
    /// </summary>
    public partial class App : Application
    {
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            // load SDK loacation from installer
            string folder = GetSdkFolder();
            if (string.IsNullOrEmpty(folder))
                MessageBox.Show(WPF_ScanControl_Sample.Properties.Resources.MsgSdkFolderNotFound, 
                    WPF_ScanControl_Sample.Properties.Resources.TitleApp,
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
            else
                CustomDllResolver.InitializeAssembly(folder);

            AppDomain.CurrentDomain.UnhandledException += HandleOtherExceptions;
        }

        private static string GetSdkFolder()
        {
            const string keyName32 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{CEEBC446-FF29-47FF-B286-88EF80F9F7EE}";
            const string keyName64 = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{CEEBC446-FF29-47FF-B286-88EF80F9F7EE}";

            try
            {
                RegistryKey regKey;
                if (Environment.Is64BitOperatingSystem)
                    regKey = Registry.LocalMachine.OpenSubKey(keyName64);
                else
                    regKey = Registry.LocalMachine.OpenSubKey(keyName32);
                if (regKey != null)
                {
                    string installedRoot = regKey.GetValue("InstallLocation").ToString();
                    regKey.Close();
                    regKey.Dispose();
                    if (!string.IsNullOrEmpty(installedRoot))
                    {
                        string sdkFolder = Path.Combine(installedRoot, @"Redist\PPScanControl");
                        return sdkFolder;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }

        private void HandleOtherExceptions(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            string msg = ex?.Message ?? e.ExceptionObject.ToString();
            MessageBox.Show(msg,
                WPF_ScanControl_Sample.Properties.Resources.TitleApp,
                MessageBoxButton.OK,
                MessageBoxImage.Warning);
            Shutdown(-1);
        }
    }
}
