using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Siger.Middlelayer.Log;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Siger.Middlelayer.Common;
using Siger.ApiCommon.Utilities;
using Siger.Middlelayer.Redis;
using Microsoft.Extensions.Hosting;

namespace Siger.Middlelayer.ApiGateway
{
    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")) ;
            });
            var config = new ConfigurationBuilder().AddJsonFile("Setting/OcelotSetting.json").Build();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddOcelot(config);
            Logger.RegisterLogEngine(Module.Gateway);
            //Cors.AddCors(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.RegisterDownSetting();
            app.UseCors(_corsKeyName);
            app.UseOcelot().Wait();
            //app.UseMvc();
            lifetime.ApplicationStopped.Register(RedisCache.Instance.Dispose);
        }
    }
}
