using LogoForceTestApp.Modules.MainModule.Models;
using LogoForceTestApp.Modules.MainModule;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Modularity;
using Serilog.Events;
using Serilog;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using LogoForceTestApp.Services.Interfaces;
using LogoForceTestApp.Services;
using LogoForceTestApp.Views;
using DryIoc;
using Team.Utility;
using DryIoc.Microsoft.DependencyInjection;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
using Repository;
using Microsoft.EntityFrameworkCore;
using AutoMapper.EquivalencyExpression;
using System.Linq;
using System.Reflection;
using TouchSocket.Sockets;
using System.Text;
using TouchSocket.Core;
using LogoForceTestApp.Modules.MainModule.Views;
using Prism.Events;
using AutoMapper;
using Mapper = AutoMapper.Mapper;
using LogForceTestApp.Modules.MainModule;


namespace LogoForceTestApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App
    {
        private static readonly string logPath = AppDomain.CurrentDomain.BaseDirectory + "logs.db";
        private readonly ILogger _log = new LoggerConfiguration()
           .WriteTo.Console(LogEventLevel.Debug)
           .WriteTo.Debug(LogEventLevel.Debug)
            .WriteTo.SQLite(logPath)
           .WriteTo.File(AppDomain.CurrentDomain.BaseDirectory + "logs/log.log", rollingInterval: RollingInterval.Day)
          .CreateLogger();
        public static string Version { get; private set; }
        protected override void OnStartup(StartupEventArgs e)
        {
            var version =Assembly.GetExecutingAssembly().GetName().Version;
            Version = version.ToString();
            var teamContext = new TeamDataContext();
            teamContext.Database.Migrate();
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            base.OnStartup(e);
        }
        protected override Window CreateShell()
        {
            Container.Resolve<KBWindow>().Show();
            //new KBWindow().Show();
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<KBWindow>();
            containerRegistry.RegisterInstance(_log);

            containerRegistry.RegisterSingleton<IRepository, Repository.Repository>();
            containerRegistry.RegisterSingleton<IModbusTcpSlaverService, ModbusTcpSlaverService>();
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.AddCollectionMappers();
                cfg.AddProfile(new MainModuleProfile());
            });
            containerRegistry.RegisterInstance(typeof(IMapper), new Mapper(configuration));
            //tcp
            TcpService tcpService = new TcpService();
            tcpService.Setup(new TouchSocketConfig()//载入配置
                .SetListenIPHosts(7790)//端口号
                .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                {
                    a.AddConsoleLogger();//添加一个控制台日志注入(注意:在maui中控制台日志不可用)
                }));

            tcpService.Start();//启动
            containerRegistry.RegisterInstance(tcpService);
        }

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

        protected override IContainerExtension CreateContainerExtension()
        {
            var services = new ServiceCollection();
            Serilog.Log.Logger = _log;
            services.AddLogging(c => c.AddSerilog());
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", false, true);
            var configuration = builder.Build();
            services.ConfigureWritable<AppSettings>(configuration.GetSection(nameof(AppSettings)));
            services.AddHttpClient();
           

            return new DryIocContainerExtension(new DryIoc.Container(CreateContainerRules())
              .WithDependencyInjectionAdapter(services));
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            _log.Information($"App TaskSchedulerUnobservedTaskException Exit:{e.Exception}");
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _log.Information($"App CurrentDomainUnhandledException Exit:{e.ExceptionObject}");
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            _log.Information($"App AppDispatcherUnhandledException Exit:{e.Exception}");
        }
    }
}