using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Hosting;
using isnd.Data;
using isnd.Interfaces;
using isnd.Services;
using isnd.Entities;
using isnd.Authorization;
using isnd.Data.Roles;
using Microsoft.AspNetCore.Authorization;
using Unleash;
using Microsoft.Extensions.Options;
using isnd.Helpers;
using Microsoft.IdentityModel.Tokens;
using System;
using Microsoft.OpenApi.Models;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Text.Json;
using System.Text.Json.Serialization;
using isnd.Data.Catalog;
using Newtonsoft.Json;
using Microsoft.AspNetCore.HttpOverrides;

namespace isnd
{

    public class Startup
    {

        public Startup(IConfiguration config)
        {
            Configuration = config;
        }

        public static IConfiguration Configuration { get; private set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var smtpSettingsconf = Configuration.GetSection("Smtp");
            var isndSettingsconf = Configuration.GetSection("Isn");
            var adminStartupListConf = Configuration.GetSection("AdminList");
            var unleashConf = Configuration.GetSection("Unleash");

            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            services.Configure<SmtpSettings>(smtpSettingsconf)
            .Configure<IsndSettings>(isndSettingsconf)
            .Configure<AdminStartupList>(adminStartupListConf)
            .Configure<UnleashClientSettings>(unleashConf)
            .Configure<MigrationsEndPointOptions>(o => o.Path = "~/migrate")
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseNpgsql(
                    Configuration.GetConnectionString("DefaultConnection")))
            .AddIdentity<ApplicationUser, IdentityRole>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddSignInManager()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

            services.AddMvc(o => o.EnableEndpointRouting = false);

            services.AddDataProtection();

            services.AddAuthorization(options =>
            {
                options.AddPolicy(IsndConstants.RequireAdminPolicyName,
                    policy => policy.RequireRole(IsndConstants.AdministratorRoleName));
                options.AddPolicy(IsndConstants.RequireValidApiKey, policy =>
                    policy.Requirements.Add(new ValidApiKeyRequirement()));

            })

            .AddTransient<IMailer, EmailSender>()
            .AddTransient<IEmailSender, EmailSender>()
            .AddTransient<IPackageManager, PackageManager>()
            .AddSingleton<IAuthorizationHandler, ValidApiKeyRequirementHandler>()
            .AddSingleton(s =>
              {
                  var config = s.GetRequiredService<IOptions<UnleashClientSettings>>();
                  if (config.Value == null)
                      throw new System.Exception("No unleash client settings");
                  if (config.Value.ApiUrl == null)
                      throw new System.Exception("No unleash client ApiUrl");
                  if (config.Value.ClientApiKey == null)
                      throw new System.Exception("No unleash client ClientApiKey");
                  return s.GetRequiredService<Microsoft.AspNetCore.Hosting.IHostingEnvironment>().CreateUnleahClient(config.Value);
              });


            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = isndSettingsconf.GetValue<string>("ExternalUrl");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
            });

            services.AddControllersWithViews()
           .AddNewtonsoftJson(s =>
           {
               s.SerializerSettings.ReferenceResolverProvider = () => new NSJWebApiReferenceResolver();
           });
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "isnd API",
                    Description = "An ASP.NET Core Web API for managing isnd items",
                    TermsOfService = new Uri("https://isn.pschneider.fr/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Example Contact",
                        Url = new Uri("https://isn.pschneider.fr/contact")
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Example License",
                        Url = new Uri("https://isn.pschneider.fr/license")
                    }
                });
                var xmlFilename = $"{typeof(Startup).Assembly.GetName().Name}.xml";
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
        IWebHostEnvironment env,
        ApplicationDbContext dbContext,
        IOptions<IsndSettings> isnSettingsOption)
        {
            app.UseForwardedHeaders();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
                dbContext.Database.Migrate();
            }
            app.UseStatusCodePages().UseStaticFiles().UseAuthentication();
            app.UseMvcWithDefaultRoute();
        }
    }
}
