using ConverterSetting.Core;
using ConverterSetting.Core.DataBase;
using DevExpress.CodeParser.Diagnostics;
using DevExpress.Xpo.Logger;
using HslCommunication.LogNet;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using UpdateFileCommon;

namespace ConverterSetting
{
    internal static class Program
    {
        private static readonly NLog.Logger _log = NLog.LogManager.GetCurrentClassLogger();
        public static ServiceProvider serviceProvider;
        public static string dataBaseUrl = AppDomain.CurrentDomain.BaseDirectory;
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = "";
            string strDateInfo = "\r\n\r\n出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            Exception error = e.Exception as Exception;
            _log.Error(error, error.Message);
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n", error.GetType().Name, error.Message, error.StackTrace);
                str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n",
                error.GetType().Name, error.Message);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}", e);
            }
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            _log.Error(error, error.Message);
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r", error.Message);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main()
        {
            bool res = HslCommunication.Authorization.SetAuthorizationCode("");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);//处理未捕获的异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            ServiceCollection services = new ServiceCollection();
        ;
            services.AddSingleton<ProjectService>();
            services.AddSingleton<DriveLogService>();

            services.AddScoped<RecentProjectFormUserControl>();
            services.AddScoped<Main>();
            services.AddScoped<ControlPanel1>();
            services.AddScoped<ParameterListUserControl>();
            services.AddScoped<MultiBaseInputForm>();
            services.AddScoped<OscilloScope>();
            services.AddScoped<OscChannelAddForm>();
            services.AddScoped<ProjectNewForm>();
            services.AddScoped<SplashScreen>();
            services.AddScoped<DriveAddForm>();
            services.AddScoped<DriveListForm>();
            services.AddScoped<FunCodeDownloadControl>();
            services.AddScoped<FunCodeUploadControl>();
            services.AddScoped<CompareDefaultUserControl>();
            services.AddScoped<SettingStepPageControl>();
            services.AddScoped<DriveFaultUserControl>();
            services.AddScoped<DriveStateUserControl>();
            services.AddScoped<DriveLogUserControl>();
            services.AddScoped<MotorParameterTestControl>();
            services.AddScoped<SystemUpdateForm>();
            services.AddScoped<TestControlPanel>();
            

            //services.AddHttpContextAccessor();
            services.AddScoped<SqlSugarClient>(s =>
            {
                //Scoped用SqlSugarClient
                SqlSugarClient sqlSugar = new SqlSugarClient(new List<ConnectionConfig>() {
                    new ConnectionConfig()
                    {
                        ConfigId="0",
                        ConnectionString = $"Data Source={dataBaseUrl}/MOVITIC-1.db",
                        DbType = SqlSugar.DbType.Sqlite,         //必填, 数据库类型
                        IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                        InitKeyType = InitKeyType.SystemTable
                    },
                    new ConnectionConfig()
                    {
                        ConfigId="1",
                        ConnectionString = $"Data Source={dataBaseUrl}/MOVITIC-2.db",
                        DbType = SqlSugar.DbType.Sqlite,         //必填, 数据库类型
                        IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                        InitKeyType = InitKeyType.SystemTable
                    },
                    new ConnectionConfig()
                    {
                        ConfigId="2",
                        ConnectionString = $"Data Source={dataBaseUrl}/MOVITIC-3.db",
                        DbType = SqlSugar.DbType.Sqlite,         //必填, 数据库类型
                        IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                        InitKeyType = InitKeyType.SystemTable
                    }
                },
               db =>
               {
                   //每次上下文都会执行

                   //获取IOC对象不要求在一个上下文
                   //var log=s.GetService<Log>()

                   //获取IOC对象要求在一个上下文
                   //var appServive = s.GetService<IHttpContextAccessor>();
                   //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                   };
               });
                return sqlSugar;
            });

            serviceProvider = services.BuildServiceProvider();
            var main = serviceProvider.GetService<Main>();
            //默认的LoginView为登陆窗体

            ApplicationContext context = new ApplicationContext(main);

            Application.Run(context);
        }


        public static T GetService<T>()
        {
            IServiceScope scope = serviceProvider.CreateScope();
            var service = scope.ServiceProvider.GetService<T>();
            return service;
        }
    }
}