using Prism.Ioc;
using Prism.Modularity;
using StartServerWPF.Modules.Main;
using StartServerWPF.Views;
using System.Collections;
using System.Net.NetworkInformation;
using System.Text;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using StartServerWPF.Modules.MseedChart;
using Newtonsoft.Json;
using System.IO;
using StartServerWPF.Models;
using System.Collections.Generic;
using System.Linq;

namespace StartServerWPF
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {

        public App()
        {
            System.AppDomain.CurrentDomain.UnhandledException += new System.UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<WebsocketClient>();

            string str = File.ReadAllText("SystemConfig.json");
            SystemConfigModel sc = JsonConvert.DeserializeObject<SystemConfigModel>(str);
            containerRegistry.RegisterSingleton<SystemConfigModel>(() => sc);

            string st = File.ReadAllText(Path.Combine(JsonParser.workareaPath, "Workareas.json"));
            var wm = JsonConvert.DeserializeObject<WorkareasModelArray>(st);
            var item = wm.workarea[wm.selectIndex];
            string areaPath = Path.Combine(item.filepath, Path.GetFileName(item.filepath)+".json");
            var currentWorkarea =new WorkareaModel();
            if (File.Exists(areaPath))
            {
                string workarea = File.ReadAllText(areaPath);
                currentWorkarea = JsonConvert.DeserializeObject<WorkareaModel>(workarea);

                if (currentWorkarea.StationConfig.Stations == null)
                {
                    currentWorkarea.StationConfig.Stations = currentWorkarea.CreateStationFromCSV(Path.Combine(JsonParser.workareaPath, currentWorkarea.apmModel.station), currentWorkarea.StationConfig.Location)
                                              ?.Select(a => new StationState { IsEnable = a.Enable, Name = a.Num }).ToList();
                }
            }
            else
            {
                //加载默认配置数据
                string workarea = File.ReadAllText(Path.Combine(JsonParser.workareaPath, "Workarea.json"));
                currentWorkarea = JsonConvert.DeserializeObject<WorkareaModel>(workarea);
            }
            containerRegistry.RegisterSingleton<WorkareasModelArray>(() => wm);
            containerRegistry.RegisterSingleton<WorkareaModel>(() => currentWorkarea);
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<MainModule>();
            moduleCatalog.AddModule<MseedChartModule>();
            base.ConfigureModuleCatalog(moduleCatalog);
        }


        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                System.Exception error = (System.Exception)e.ExceptionObject;
                StringBuilder stringBuilder = ExtractAllStackTrace(error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// UI线程未捕获异常处理事件（UI主线程）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder = ExtractAllStackTrace(e.Exception);
            //if (e.Exception.InnerException != null)
            //{
            //    stringBuilder.AppendFormat("\n\r {0}", e.Exception.InnerException);
            //    stringBuilder.AppendFormat("\n\r {0}", e.Exception.InnerException.StackTrace);
            //}
            //stringBuilder.AppendFormat("\n\r {0}", e.Exception.StackTrace);
            //string errmsg;
            //if (e.Exception is XamlParseException && e.Exception.InnerException != null)
            //{
            //    errmsg = e.Exception.InnerException.Message;
            //}
            //else
            //{
            //    errmsg = e.Exception.Message;
            //}

            e.Handled = true;
        }

        //Task线程内未捕获异常处理事件
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder = ExtractAllStackTrace(e.Exception);
            //Exception ex = e.Exception;
            //string msg = String.Format("{0}\n\n{1},{2}", ex.Message, ex.StackTrace, ex.InnerException.StackTrace);
          //  new Log.GetLogger("APP.xmal").Log.Error("App.TaskScheduler_UnobservedTaskException()" + stringBuilder.ToString());

       //     WriteError(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:ffffff") + ": " + stringBuilder.ToString());
            //App.Current.Dispatcher.Invoke(() =>
            //{
            //    //MessageBoxResult messageBox = MessageBox.Show(msg, "提示", MessageBoxButton.OK);
            //    IsClickBtn? value = IsClickBtn.cancel;
            //    value = LoadError.Show(msg);
            //    if (value == IsClickBtn.yes)
            //    {

            //    }
            //    //   ViewModel.LoadViaViewModel.LoadingViewModel.ExitProcess(0);
            //});
        }

        /// <summary>
        /// 提取异常及其内部异常堆栈跟踪
        /// </summary>
        /// <param name="exception">提取的异常</param>
        /// <param name="lastStackTrace">最后提取的堆栈跟踪（对于递归）， String.Empty or null</param>
        /// <param name="exCount">提取的堆栈数（对于递归）</param>
        /// <returns>Syste.String</returns>
        private static StringBuilder ExtractAllStackTrace(Exception exception, StringBuilder lastStackTrace = null, int exCount = 1)
        {
            var ex = exception;
            //修复最后一个堆栈跟踪参数
            lastStackTrace = lastStackTrace ?? new StringBuilder();
            //添加异常的堆栈跟踪
            lastStackTrace.Append($"count:{exCount}: {ex.Message}{ex.StackTrace}\n\r");
            if (exception.Data.Count > 0)
            {
                lastStackTrace.Append("Data:");
                foreach (var item in exception.Data)
                {
                    var entry = (DictionaryEntry)item;
                    lastStackTrace.Append($"{entry.Key}: {exception.Data[entry.Key]}\n\r");
                }
            }
            //递归添加内部异常
            if ((ex = ex.InnerException) != null)
                return ExtractAllStackTrace(ex, lastStackTrace, ++exCount);
            return lastStackTrace;
        }
    }
}
