using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Siger.ApiCommon.Filters;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.WmsRepository;

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

        public IConfiguration Configuration { get; }
        private string _corsKeyName = "Cors";
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => {
                options.AddPolicy(_corsKeyName, builder => builder.AllowAnyOrigin()
                .AllowAnyHeader().AllowAnyMethod());
                //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")) ;
            });
            services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllers().AddNewtonsoftJson(option => {
                option.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                option.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            });
            services.AddMvc(options =>
            {
                options.Filters.Add<ModelValidateFilter>();
                options.Filters.Add<ApiExceptionFilter>();
                options.Filters.Add<ResultFilter>();
                options.Filters.Add<TokenValidateFilter>();
            });
            Logger.RegisterLogEngine(Module.Wms);
            Swagger.AddSwagger(services, Module.Wms);
            WmsRepositoryFactory.Instance.Initialization(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.RegisterFileSystem();
            app.UseCors(_corsKeyName);
            app.RegisterSwagger(Module.Wms);
            app.UseMvc();
            app.RegisterConsul(Module.Wms, lifetime);
            lifetime.ApplicationStopped.Register(RedisCache.Instance.Dispose);
 
        }
    }
}
