using Autofac;
using SqlSugar;
using SqlSugar.IOC;
using WinformDevFarme;
using WinformDevFramework.Core.Autofac;
using WinformDevFramework.Core.Configuration;
using WinformDevFramework.Core.Winform;

namespace WinformDevFramework
{
    internal static class Program
    {
        public static IContainer Container { get; private set; }
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            ApplicationConfiguration.Initialize();
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            // 创建容器
            var builder = new ContainerBuilder();
            // 注册 SqlSugar 配置
            builder.Register(c =>
            {
                var db = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串
                    //DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer,
                    DbType = DbType.PostgreSQL,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute, // 如果使用实体类的属性进行主键标识，请设置为 InitKeyType.Attribute
                    MoreSettings = new SqlSugar.ConnMoreSettings()
                    {
                        PgSqlIsAutoToLower = false,
                        PgSqlIsAutoToLowerCodeFirst = false
                    }
                });
                db.Aop.OnLogExecuting = (sql, pars) =>
                {

                };
                return db;
            }).As<ISqlSugarClient>().InstancePerLifetimeScope();

            //获取所有窗体类型
            var baseType = typeof(Form);
            builder.RegisterAssemblyTypes(typeof(Program).Assembly)
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces()
                .InstancePerDependency()
                .Named(t => t.Name, typeof(Form));
            builder.RegisterModule(new AutofacModuleRegister());
            // 构建容器
            Container = builder.Build();
            AppInfo.Container = Container;
            Application.Run(Container.ResolveNamed<Form>("FrmLogin"));
        }
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
        {
            var result = MessageBox.Show("系统发生错误，您需要退出系统吗？", "异常", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
    }
}