using AipGateway.API.Service.Repositories;
using AipGateway.API.Service.Services;
using AipGateway.API.Service.Filters;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
using Serilog;
using AipGateway.Data;
using AipGateway.Data.Entities;
using Microsoft.EntityFrameworkCore;
using AipGateway.API.Service.Configurations;

// https://lab.cliel.com/entry/ASPNET-Core-9-%EA%B3%A0%EA%B8%89-Web-Service-%EA%B8%B0%EB%8A%A5

//Log.Logger = new Serilog.LoggerConfiguration()
//    //.WriteTo.Console()
//    .WriteTo.AzureApp()
//    .CreateBootstrapLogger();
internal class Program
{
    [Obsolete]
    private static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Start Azure Information RESTFull API Service... [{0}]", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));

            //Log.Logger = new LoggerConfiguration()
            //    //.ReadFrom.Configuration(configuration)
            //    .CreateLogger();
            
            var builder = WebApplication.CreateBuilder(args);

            ConfigureSettings(builder.Host, builder.Environment);
            AddAppSettings(builder.Services, builder.Configuration);
            ConfigureServices(builder.Services, builder.Configuration);


            LinkedServerRepository linkedServerRepository = new LinkedServerRepository();
            builder.Services.AddSingleton<ILinkedServerRepository>(linkedServerRepository);
            builder.Services.AddSingleton<ILinkedServerService>(new LinkedServerService(linkedServerRepository));
            builder.Services.AddSingleton<IAipFileManagerService>(new AipFileManagerService());

            builder.Services.AddControllers().AddNewtonsoftJson();

            // Add services to the container.
            //builder.Services.AddControllersWithViews();

            builder.Services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            builder.Services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


            builder.Services.Configure<MvcOptions>(opts => {
                opts.RespectBrowserAcceptHeader = true;
                opts.ReturnHttpNotAcceptable = true;
            });

            //builder.Services.AddSwaggerGen(c => {
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Azure Information Protection RESTFull API Service Gateway", Version = "v1" });
            //});

            builder.Services.Configure<MvcNewtonsoftJsonOptions>(opts => {
                opts.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });
            builder.Services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            builder.WebHost.ConfigureKestrel((context, serverOptions) =>
            {
                serverOptions.ListenAnyIP(5000);
            });
            //https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-8.0
            //builder.WebHost.ConfigureKestrel((context, serverOptions) =>
            //{
            //serverOptions.Limits.MaxRequestBodySize = 100_000_000;
            //serverOptions.Limits.MaxConcurrentConnections = 100;
            //serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
            //serverOptions.Listen(IPAddress.Any, 8000, listenOptions =>
            //{
            //listenOptions.UseHttps("testCert.pfx", "testPassword");
            //listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
            //});
            //});

            var app = builder.Build();

            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            //app.MapControllerRoute(
            //    name: "default",
            //    pattern: "{controller=Home}/{action=Index}/{id?}");

            app.MapControllers();

            //app.UseForwardedHeaders(new ForwardedHeadersOptions
            //{
            //    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            //});

            //app.UseForwardedHeaders(new ForwardedHeadersOptions
            //{
            //    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, //ForwardedHeaders.All,
            //RequireHeaderSymmetry = false,
            //ForwardLimit = null,
            //KnownNetworks = { new System.Net.IPNetwork(IPAddress.Parse("::ffff:172.17.0.1"), 104) }
            //});

            //app.UseMiddleware<MyWebApp.TestMiddleware>();
            app.UseSwagger();
            app.UseSwaggerUI(options => {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "AipAPI");
            });

            app.Run();
        }
        catch (Exception ex) when (ex.GetType().Name is not "StopTheHostException"
            && ex.GetType().Name is not "HostAbortedException")
        {
            Log.Fatal(ex, "Unhandled exception");
        }
        finally
        {
            Log.Information("Shut down complete");
            Log.CloseAndFlush();
        }
    }

    private static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        //services.AddRazorPages();
        services.AddControllers(options =>
        {
            options.Filters.Add<ExceptionFilter>();
            options.Filters.Add<AipApiAsyncActionFilter>();
            options.Filters.Add<AipApiActionFilter>();

        });
        
        // If you want to use the Action Filter in Controller or Action Level 
        // You need to register the Action-Filter-Class first
        //services.AddTransient<ActionFilterEx1>();
        //services.AddTransient<ActionFilterEx2>();
        //services.AddTransient<ControllerActionFilter>();
        //services.AddTransient<ValidateActionFilter>();

        SwaggerConfiguration(services, configuration);

        ApplicationContextConfiguration(services, configuration);
        //JwtTokenConfiguration(services, configuration);

        //AddApplicationServices(services);
    }
    private static void ApplicationContextConfiguration(IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<AipDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

        //services
        //    .AddDefaultIdentity<ApplicationUser>(IdentityOptionsProvider.GetIdentityOptions)
        //    .AddRoles<ApplicationRole>()
        //    .AddEntityFrameworkStores<ApplicationContext>();
    }


    private static void AddApplicationServices(IServiceCollection services)
    {
        //services.AddScoped<IAccountService, AccountService>();
        //services.AddScoped<IJwtTokenManager, JwtTokenManager>();
        //services.AddScoped<IEmailSenderService, EmailSenderService>();
        //services.AddScoped<IRoleService, RoleService>();
        //services.AddScoped<IUserService, UserService>();
    }

    private static void SwaggerConfiguration(IServiceCollection services, IConfiguration configuration)
    {
        SwaggerSettings swaggerSettings = new();
        configuration.GetSection(nameof(SwaggerSettings)).Bind(swaggerSettings);

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc(swaggerSettings.Version, new OpenApiInfo
            {
                Title = swaggerSettings.Title,
                Version = swaggerSettings.Version,
            });
        });
    }

    private static void ConfigureSettings(IHostBuilder hostBuilder, IHostEnvironment environment)
    {
        hostBuilder.ConfigureAppConfiguration(config =>
        {
            config
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(
                    path: "appsettings.json",
                    optional: false,
                    reloadOnChange: true)
                .AddJsonFile(
                    path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
                    optional: true,
                    reloadOnChange: true)
                .AddEnvironmentVariables();
        });
    }

    private static void AddAppSettings(IServiceCollection services, IConfiguration configuration)
    {
        //services.Configure<JwtTokenSettings>(configuration.GetSection(nameof(JwtTokenSettings)));
        //services.Configure<EmailSenderSettings>(configuration.GetSection(nameof(EmailSenderSettings)));
        //services.Configure<RequestLocalizationSettings>(configuration.GetSection(nameof(RequestLocalizationSettings)));
        if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") {
            services.Configure<SwaggerSettings>(configuration.GetSection(nameof(SwaggerSettings)));
        }
    }

}
