using Autofac;
using Infrastructure;
using Infrastructure.Extensions.AutofacManager;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.IdentityModel.Tokens;
using OpenAuth.App;
using OpenAuth.Mvc.Models;
using OpenAuth.Repository;
using SqlSugar;

namespace OpenAuth.Mvc
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //在startup中需要强制创建log4net
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddLog4Net();
            });
            ILogger logger = loggerFactory.CreateLogger<Startup>();
            var identityServer = ((ConfigurationSection)Configuration.GetSection("AppSetting:IdentityServerUrl")).Value;
            if (!string.IsNullOrEmpty(identityServer))
            {
                System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

                services.AddAuthentication(options =>
                    {
                        options.DefaultScheme = "Cookies";
                        options.DefaultChallengeScheme = "oidc";
                    })
                    .AddCookie("Cookies")
                       .AddOpenIdConnect("oidc", options =>
                       {
                           options.Authority = identityServer;
                           options.RequireHttpsMetadata = false;

                           options.ClientId = "OpenAuth.Mvc";
                           options.SaveTokens = true;
                           options.TokenValidationParameters = new TokenValidationParameters
                           {
                               NameClaimType = "name",
                               RoleClaimType = "role",
                           };

                           options.NonceCookie.SameSite = SameSiteMode.Unspecified;
                           options.CorrelationCookie.SameSite = SameSiteMode.Unspecified;
                       });
            }

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //关闭GDPR规范
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddControllersWithViews(option =>
            {
                option.Filters.Add<OpenAuthFilter>();
                option.ModelBinderProviders.Insert(0, new JsonBinderProvider());
            });

            services.AddMemoryCache();
            services.AddOptions();

            services.AddRouting(options => options.LowercaseUrls = false);

            //映射配置文件
            services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));

            #region SqlSugar
            ////没有直接 using SqlSugar，因为如果引用命名空间的话，会和Microsoft的一个GetTypeInfo存在二义性，所以就直接这么使用了
            services.AddScoped<ISqlSugarClient>(s =>
            {
                StaticConfig.CustomSnowFlakeFunc = () =>
                {
                    return Yitter.IdGenerator.YitIdHelper.NextId();
                };

                var sqlSugar = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.PostgreSQL,
                    ConnectionString = Configuration.GetConnectionString("OpenAuthDBContext"),
                    IsAutoCloseConnection = true,
                    MoreSettings = new SqlSugar.ConnMoreSettings()
                    {
                        PgSqlIsAutoToLower = false,
                        PgSqlIsAutoToLowerCodeFirst = false
                    }
                },
               db =>
               {
                   //单例参数配置，所有上下文生效
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       //        //Console.WriteLine(sql + "\r\n" +
                       //        //db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                       //        //Console.WriteLine();
                   };
               });
                return sqlSugar;
            });

            services.AddScoped<ISugarUnitOfWork<SugarDbContext>, SugarUnitOfWork<SugarDbContext>>();
            //services.AddScoped<SqlSugar.ISugarUnitOfWork<SugarDbContext>>(s => new SqlSugar.SugarUnitOfWork<SugarDbContext>(s.GetService<ISqlSugarClient>()));
            #endregion

            services.AddHttpClient();

            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Configuration["DataProtection"]));

            //设置定时启动的任务
            //services.AddHostedService<QuartzService>();

        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            AutofacExt.InitAutofac(builder);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();

            //配置ServiceProvider
            AutofacContainerModule.ConfigServiceProvider(app.ApplicationServices);

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

        }
    }
}
