using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.AccRepository;
using Siger.Middlelayer.CncRepository;
using Siger.Middlelayer.CncRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.TlmRepository;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;

namespace Siger.ApiChangLing
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        private string _corsKeyName = "Cors";

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => {
                options.AddPolicy(_corsKeyName, builder => builder.AllowAnyOrigin()
                .AllowAnyHeader().AllowAnyMethod());
            });
            services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddMvc(options =>
            {
                options.Filters.Add<ModelValidateFilter>();
                options.Filters.Add<ApiExceptionFilter>();
                options.Filters.Add<ResultFilter>();
                options.Filters.Add<TokenValidateFilter>();
            });
            services.AddControllers().AddNewtonsoftJson(option => {
                option.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                option.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            });

            Logger.RegisterLogEngine(Module.ChangLing);
            AccRepositoryFactory.Instance.Initialization(services);
            CncRepositoryFactory.Instance.DiRepositories(services, typeof(ICncRepositoryBase<>));
            TlmRepositoryFactory.Instance.DiRepositories(services, typeof(ITlmRepositoryBase<>));
            services.AddDbContext<ApiTlmDbContext>();
            services.AddDbContext<ApiCncDbContext>();

            Swagger.AddSwagger(services, Module.ChangLing);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.RegisterFileSystem();
            app.UseCors(_corsKeyName);
            app.UseMvc();
            app.RegisterSwagger(Module.ChangLing);
            lifetime.ApplicationStopped.Register(RedisCache.Instance.Dispose);
        }
    }
}
