using ButcherFactory.BO.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using WinFormControl;

namespace ButcherFactory.Login
{
  /// <summary>
  /// App.xaml 的交互逻辑
  /// </summary>
  public partial class App : Application
  {
    public EventWaitHandle ProgramStarted { get; set; }

    readonly string[] FOLDERS = new string[] { "Config", "PrintTemplate", "Log", "TempImg" };

    protected override void OnStartup(StartupEventArgs e)
    {
      bool createNew;
      ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "ButcherFactorySolution", out createNew);

      if (!createNew)
      {
        UMessageBox.Show(@"系统已经在运行中，如果要重新启动，请从进程中关闭...", @"系统警告");
        App.Current.Shutdown();
      }

      System.Windows.Forms.Application.EnableVisualStyles();
      System.Windows.Forms.Application.SetUnhandledExceptionMode(System.Windows.Forms.UnhandledExceptionMode.CatchException);
      System.Windows.Forms.Application.ThreadException += Application_ThreadException;

      RegisterEvents();
      base.OnStartup(e);
      foreach (var folder in FOLDERS)
      {
        if (!System.IO.Directory.Exists(folder))
          System.IO.Directory.CreateDirectory(folder);
      }
      var tempImages = new System.IO.DirectoryInfo("TempImg").GetFiles();
      foreach (var f in tempImages)
        f.Delete();
      if (e.Args.Length == 1 && e.Args[0] == "true")
        UpdateDb();
    }

    ///<summary>
    ///  在发生未处理异常时处理的方法
    ///</summary>
    ///<param name="sender"> </param>
    ///<param name="e"> </param>
    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
      var ex = e.Exception;
      var err = String.Empty;
      if (ex != null)
      {
        //LogUtil.WriteError(ex);
        err = ex.Message;
      }
      SoundPalyUtil.PlaySound(SoundType.Error);
      MessageBox.Show("错误：" + ex.Message + " \n详细信息：" + ex.StackTrace);
      //  UMessageBox.Show("错误：" + err);
    }

    private void RegisterEvents()
    {
      DispatcherUnhandledException += App_DispatcherUnhandledException;

      TaskScheduler.UnobservedTaskException += (sender, args) =>
      {
        SoundPalyUtil.PlaySound(SoundType.Error);

        MessageBox.Show("错误：" + args.Exception.Message + " \n详细信息：" + args.Exception.StackTrace);
        args.SetObserved();
      };

      AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
      {
        SoundPalyUtil.PlaySound(SoundType.Error);
        MessageBox.Show("Unhandled exception." + args.ExceptionObject);
      };
    }


    void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
      SoundPalyUtil.PlaySound(SoundType.Error);
      MessageBox.Show("错误：" + e.Exception.Message + " \n详细信息：" + e.Exception.StackTrace);
      e.Handled = true;
    }

    void UpdateDb()
    {
      try
      {
        if (!string.IsNullOrEmpty(BO.Utils.AppContext.ConnectInfo.SqlConnection))
        {
          DbUtil.UpdateDatabase(BO.Utils.AppContext.ConnectInfo.SqlConnection);
        }
      }
      catch
      {
#if DEBUG
        throw;
#endif
      }
    }
  }
}
