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;

namespace isnd
{
    public class Startup
    {
        public Startup(IConfiguration config)
        {
            Configuration = config;

        }

        public IConfiguration Configuration { get; }

        // 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<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();
            
            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 = "https://localhost:5001";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
            });

        }


        public static IUnleash UnleashĈlient { get; private set; }
        public static string ExternalAddress { get; internal set; }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, 
        Microsoft.AspNetCore.Hosting.IHostingEnvironment env,
        ApplicationDbContext dbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                // app.UseExceptionHandler("/Home/Error");
                app.UseDeveloperExceptionPage();
                dbContext.Database.Migrate();
            }
            
            app.UseStatusCodePages().UseStaticFiles().UseAuthentication().UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}");
            });
        }
    }
}
