using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Performance.Subsidy.Api.Filters;
using Performance.Subsidy.Services;
using Performance.Subsidy.Services.Models;
using Performance.Subsidy.Services.Repository;

namespace Performance.Subsidy.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            var connectionString = Configuration.GetConnectionString("DefaultConnectionString");

            builder.RegisterType<SubsidyService>().InstancePerLifetimeScope();
            builder.RegisterType<ConnectionStringBuilder>().SingleInstance();
            builder.RegisterInstance(new ConnectionFactory(connectionString)).SingleInstance();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Performance.Subsidy.Api", Version = "v1" });
            });
            services.Configure<ConnectionStringTemplates>(Configuration.GetSection("ConnectionStringTemplates"));

            services.AddMvc(option => { option.Filters.Add<ExceptionsFilter>(); });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string swaggerJson = "/api/swagger/v1/swagger.json";
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                swaggerJson = swaggerJson.Replace("/api", "");
            }

            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint(swaggerJson, "Performance.Subsidy.Api v1"));

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
