using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Performance.Api.Configurations;
using Performance.Infrastructure;
using Performance.Services;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace Performance.Api
{
    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)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // appsettings.json
            services.AddAppSettingConfiguration(Configuration);

            // ratelimit
            services.AddRateLimitConfiguration(Configuration);

            // graphql
            services.AddGraphQLSchemaAndTypes();

            #region json & fluentvalidation & filter

            services
                //筛选器配置
                .AddMvc(option =>
                {
                    option.Filters.Add<AuthenticationFilter>();
                    option.Filters.Add<ActionsFilter>();
                    option.Filters.Add<ExceptionsFilter>();
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                //json格式配置
                .AddJsonOptions(json =>
                {
                    json.SerializerSettings.Converters.Add(new IsoDateTimeConverterContent() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                    json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
                    json.SerializerSettings.ContractResolver = new LowercaseContractResolver();
                    json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
                    json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                    json.SerializerSettings.Culture = new CultureInfo("zh-CN");
                    json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                })
                //model验证
                .AddFluentValidation(fv =>
                {
                    //禁用其他以使FluentValidation是唯一执行的验证库
                    fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;

                    var assembly = Assembly.Load("Performance.DtoModels");
                    var types = ReflectionHelper.GetInstances<IValidator>(assembly);
                    foreach (var type in types)
                    {
                        fv.RegisterValidatorsFromAssemblyContaining(type.GetType());
                    }
                });

            #endregion json & fluentvalidation & filter

            // dbcontext
            services.AddDatabaseConfiguration();

            // automapper
            services.AddAutoMapperConfiguration();

            // swagger
            services.AddSwaggerConfiguration();

            // service repository
            services.AddDependencyInjectionConfiguration();

            // signalr
            services.AddSignalR();

            // cors
            services.AddCors(options =>
            {
                options.AddPolicy("SignalrCore", policy =>
                {
                    policy.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            app.UseCors("SignalrCore");

            app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/performance/allotLogHub"));

            loggerFactory.CreateLogger<Startup>().LogDebug(env.EnvironmentName);

            app.UseRateLimitSetup();
            
            app.UseMvc();

            app.UseSwaggerSetup(Configuration);
        }
    }

    #region hangfire 权限

    public class HangfireAuthorizationFilter : Hangfire.Dashboard.IDashboardAuthorizationFilter
    {
        //这里需要配置权限规则
        public bool Authorize(Hangfire.Dashboard.DashboardContext context)
        {
            return true;
        }
    }

    #endregion hangfire 权限
}
