// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IRaCIS.Core.IdentityServer4.Account;
using IdentityServer4.Configuration;
using Microsoft.EntityFrameworkCore;
using IRaCIS.Core.Infra.EFCore;
using IdentityServer4.Services;
using ReturnUrlParser = IRaCIS.Core.IdentityServer4.Account.ReturnUrlParser;
using Microsoft.AspNetCore.Http;

namespace IRaCIS.Core.IdentityServer4
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSameSiteCookiePolicy();

            services.AddDbContext<IRaCISDBContext>(options =>
            {
                options.UseSqlServer(Configuration.GetSection("ConnectionStrings:RemoteNew").Value,
                    contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure());

                options.EnableSensitiveDataLogging();



            }, ServiceLifetime.Scoped);

            services.AddTransient<IReturnUrlParser, ReturnUrlParser>();

            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            services.AddCors(options =>
            {
                options.AddPolicy("Limit", policy =>
                {
                    policy
                    .SetIsOriginAllowed(_ => true)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            var builder = services.AddIdentityServer(options =>
            {
                //options.Cors.CorsPaths.Add(new PathString("/connect/authorize"));
                //options.Cors.CorsPaths.Add(new PathString("/connect/authorize/callback"));
                //options.Cors.CorsPaths.Add(new PathString("/user/login"));
                //options.Cors.CorsPaths.Add(new PathString("/user/logout"));

                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;

                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;

                options.UserInteraction = new UserInteractionOptions
                {
                    //LoginUrl = "http://localhost:8082",
                    //LogoutUrl = "http://localhost:8082"

               LoginUrl = "http://localhost:8082/index.html",
               ErrorUrl = "http://localhost:8082/error.html",
               LogoutUrl = "http://localhost:8082/logout.html",
                //LoginUrl = "/user/login",
                //    LogoutUrl = "/user/logout"
                };
            });
            //.AddProfileService<AdminProfileService>()
            //.AddResourceOwnerValidator<AdminResourceOwnerPasswordValidator>();

            // in-memory, code config
            builder.AddInMemoryIdentityResources(Config.IdentityResources);
            builder.AddInMemoryApiScopes(Config.ApiScopes);
            builder.AddInMemoryClients(Config.Clients);
           
            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();

        }

        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("Limit");
            app.UseCookiePolicy();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();

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