using InitializerModel;
using MesAdaptor;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace AwInitilizer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App() : base()
        {
            SetUiLanguage();
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }

        private bool onlyOnce = true;
        private async void Test()
        {
            if (!onlyOnce)
            {
                return;
            }
            onlyOnce = false;

            //var test = new SajectConnectSajet2("ATC_TEST01");
            //bool result = false;
            //result = test.SajetTransStart();
            //await Task.Delay(5_000);
            //string userId = "001";
            //result = test.SajetTransSignIn(ref userId);
            //await Task.Delay(5_000);
            //result = test.SajetTransSnCheck("6300D000033-R00", "PL110001006");
            //result = test.SajetTransReport("6300D000033-R00", "PL110001006" , new Dictionary<string, string>() { {"Header1","Value1"} });
            //result = test.SajetTranFinishFail("6300D000033-R00", "PL110001006", MesErrorCode.BlueButtonTestFail);
            //result = test.SajetTranFinishSuccess("6300D000033-R00", "PL110001006");
            //result = test.SajetTransClose();
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);

            SetUiLanguage();

            Test();
        }

        private void SetUiLanguage()
        {
            var langSetting = AppSettingConfig.Instance.Language;

            if (langSetting.ToLower() == "zh-chs")
            {
                Resx.AppResources.Culture = System.Globalization.CultureInfo.GetCultureInfo("zh-CHS");
            }
            else
            {
                Resx.AppResources.Culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
            }
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            var msg = e.Exception.Message + "\n" + e.Exception.StackTrace;
            File.WriteAllText(fileName, msg);
            MessageBox.Show($"App crashed,Please report error and send back {fileName}");
            Application.Current.Shutdown();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            if (SajetConnect.Instance != null)
            {
                var stopResult = SajetConnect.SajetTransClose();
            }
            Environment.Exit(0);
        }
    }
}