using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using LAPS_XMLQC_Service.Controllers.Master.User;
using LAPS_XMLQC_Service.Models;
using Microsoft.Extensions.Hosting;
using LAPS_XMLQC_Service.Services;
using LAPS_XMLQC_Service.Controllers.WorkArea;
using LAPS_XMLQC_Service.App_Data;
using Npgsql;
using System.Data;

namespace LAPS_XMLQC_Service
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                  .SetBasePath(env.ContentRootPath)
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            Configuration = builder.Build();
        }

        static public IConfigurationRoot Configuration { get; set; }

        // 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();

            // Add CORS policy here
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                    builder.SetIsOriginAllowed(_ => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });


            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy",
            //        builder => builder.WithOrigins("http://localhost:4200")
            //        .AllowAnyMethod()
            //      .AllowAnyHeader()
            //        .AllowCredentials());
            //});

            services.AddSingleton<IConfiguration>(Configuration);

            // Configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<Appsettings>(appSettingsSection);

            // Configure JWT authentication
            var appSettings = appSettingsSection.Get<Appsettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // Return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            // Register services
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IWorkAreaService, WorkAreaService>();
            services.AddScoped<FileSearchService>();
            services.AddScoped<RegexPatternService>();
            services.AddScoped<XmlValidatorService>();
            services.AddScoped<CommonRepository>();
            services.AddScoped<GrantFolderPermission>();
            services.AddScoped<IImpartunateFactory, ImpartunateFactory>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            // This middleware is for handling empty content responses
            app.Use(async (ctx, next) =>
            {
                await next();
                if (ctx.Response.StatusCode == 204) // No Content
                {
                    ctx.Response.ContentLength = 0;
                }
            });

            // Enable authentication middleware
            app.UseAuthentication();

            // Use HTTPS redirection
            app.UseHttpsRedirection();

            // Enable routing
            app.UseRouting();

            // Apply CORS policy here
            app.UseCors("CorsPolicy");

            app.UseCors("AllowAll");

            // Enable authorization
            app.UseAuthorization();

            // Map controllers to the pipeline
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
