using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Diagnostics;
using System.Reflection;
using Txgy.RBS.Framework;
using Txgy.RBS.Framework.RedisHelper.Init;
using Txgy.RBS.Framework.RedisHelper.Service;
using Txgy.RBS.Services;

namespace Txgy.RBS.Server.WebApi.Register
{
    public static class HostBuilderExtend
    {
        public static void Register(this WebApplicationBuilder applicationBuilder)
        {
            //替换容器Autofac
            applicationBuilder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            applicationBuilder.Host.ConfigureContainer<ContainerBuilder>(ConfigurationBinder =>
            {
                //ConfigurationBinder.RegisterType<UserManagerService>().As<IUserManagerService>();

                #region 通过接口和实现类所在程序集注册 
                Assembly interfaceAssembly = Assembly.Load("Txgy.RBS.Services");
                Assembly serviceAssembly = Assembly.Load("Txgy.RBS.IServices");
                ConfigurationBinder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces();
                #endregion
                var pro = applicationBuilder.Configuration.GetSection("process").Get<ProcessConfig>();
                ConfigurationBinder.RegisterType<ProcessManagerService>().SingleInstance();
                #region 注册每个控制器和抽象之间的关系
                var controllerBaseType = typeof(ControllerBase);
                ConfigurationBinder.RegisterAssemblyTypes(typeof(Program).Assembly)
                    .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType);
                #endregion

                #region 注册SqlSugar 
                ConfigurationBinder.Register<ISqlSugarClient>(context =>
                {
                    SqlSugarClient client = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = applicationBuilder.Configuration.GetConnectionString("ConnectionSqlite"), // "Data Source=DESKTOP-T2D6ILD;Initial Catalog=LiveBackgroundManagementNew;Persist Security Info=True;User ID=sa;Password=sa123",
                        DbType = DbType.Sqlite,
                        InitKeyType = InitKeyType.Attribute,
                        //SlaveConnectionConfigs = new List<SlaveConnectionConfig> {
                        //         new SlaveConnectionConfig(){
                        //              ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=LiveBackgroundManagementNew;Persist Security Info=True;User ID=sa;Password=sa123",
                        //               HitRate=10
                        //         }
                        // }
                    });
                    //支持sql语句的输出，方便排除错误
                    client.Aop.OnLogExecuting = (sql, par) =>
                    {
                        Console.WriteLine("\r\n");
                        Console.WriteLine($"Sql语句:{sql}");
                        Console.WriteLine($"=========================================================================================================================================================================================================");
                    };
                    return client;
                });

                #endregion

                #region 注册Redis
                {
                    ConfigurationBinder.RegisterType<RedisHashService>();
                    ConfigurationBinder.RegisterType<RedisListService>();
                    ConfigurationBinder.RegisterType<RedisSetService>();
                    ConfigurationBinder.RegisterType<RedisStringService>();
                    ConfigurationBinder.RegisterType<RedisZSetService>();
                    //启动redis服务
                    {
                        //* Create your Process
                        Process process = new Process();
                        process.Exited += Process_Exited;
                        process.EnableRaisingEvents = true;
                        process.StartInfo.FileName = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonData.RedisDefaultPath, "server.exe"));
                        process.StartInfo.WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonData.RedisDefaultPath);
                        // process.StartInfo.Arguments = "service.conf";
                        Debug.WriteLine($"*******ProcessName:{process.StartInfo.FileName}, arguments:{process.StartInfo.Arguments}*********");
                        process.StartInfo.UseShellExecute = true;
                        process.StartInfo.CreateNoWindow = false;
                        //* Start process and handlers
                        Process[] localByName = Process.GetProcessesByName("server");

                        if (localByName.Length != 0)
                        {
                            localByName[0].Exited += Process_Exited;
                            localByName[0].EnableRaisingEvents = true;
                            process = localByName[0];
                            return;
                        }
                        bool res = process.Start();
                    }

                }
                #endregion          
            });

            applicationBuilder.Services.Configure<RedisConfigInfo>(applicationBuilder.Configuration.GetSection("RedisConfigInfo"));
        }

        private static void Process_Exited(object? sender, EventArgs e)
        {
        }
    }
}
