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 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);

            // memory cache
            services.AddMemoryCache();

            // 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)
                .AddJsonOptions(JsonOptions) //json格式配置                                            
                .AddFluentValidation(fv =>
                {
                    // model验证,禁用其他以使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();
                });
            });

            // fluentscheduler
            services.AddFluentSchedulerConfiguration();
        }

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

            app.UseMiddleware<RequestRateLimitingMiddleware>();

            app.UseCors("SignalrCore");

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

            app.UseMvc();

            app.UseSwaggerSetup(Configuration);
        }

        private void JsonOptions(MvcJsonOptions 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;
        }
    }
}
