using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PSTW_CentralSystem.CustomPolicy;
using PSTW_CentralSystem.DBContext;
using PSTW_CentralSystem.Models;
using Serilog;
using QuestPDF;
using QuestPDF.Infrastructure;
using PSTW_CentralSystem.Areas.OTcalculate.Services;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;

using System.Net;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var centralConnectionString = builder.Configuration.GetConnectionString("CentralConnnection");
        Settings.License = LicenseType.Community;

        //var inventoryConnectionString = builder.Configuration.GetConnectionString("InventoryConnection");

        // Add services to the container.
        builder.Services.AddControllersWithViews();
        builder.Services.AddRazorPages();
        builder.Services.AddScoped<OvertimeExcel>();


        builder.Services.AddScoped<NetworkShareAccess>(provider =>
            new NetworkShareAccess(@"\\192.168.12.42\images\marine\manual_tarball", "installer", "mms@pstw"));


        Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(builder.Configuration)
                    .Enrich.FromLogContext()
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Information)
                        .WriteTo.File("Logs/info-.txt", rollingInterval: RollingInterval.Day,
                            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Warning)
                        .WriteTo.File("Logs/warning-.txt", rollingInterval: RollingInterval.Day,
                            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
                        .WriteTo.File("Logs/error-.txt", rollingInterval: RollingInterval.Day,
                            outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"))
                    .WriteTo.Console()
                    .CreateLogger();

        // Set default session to 30 minutes
        builder.Services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromDays(30);
        });

        builder.Logging.AddSerilog();

        builder.Services.AddDbContext<CentralSystemContext>(options =>
        {
            options.UseMySql(centralConnectionString, new MySqlServerVersion(new Version(8, 0, 39)),
                mysqlOptions => mysqlOptions.CommandTimeout(120)
            );
        });


        builder.Services.AddDbContext<MMSSystemContext>(options =>
            options.UseMySql(builder.Configuration.GetConnectionString("MMSDatabase"),
            new MySqlServerVersion(new Version(8, 0, 0))));


        //builder.Services.AddDbContext<InventoryDBContext>(options =>
        //{
        //    options.UseMySql(inventoryConnectionString, new MySqlServerVersion(new Version(8, 0, 39)),
        //        mysqlOptions => mysqlOptions.CommandTimeout(120)
        //    );
        //});

        //builder.Services.AddDefaultIdentity<UserModel>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<AuthDBContext>();

        builder.Services.AddIdentity<UserModel, RoleModel>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<CentralSystemContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();

        builder.Services.AddAuthorizationCore(options =>
        {
            options.AddPolicy("RoleModulePolicy", policy =>
                policy.Requirements.Add(new RoleModulePolicy()));
        });

        // Add scope
        builder.Services.AddScoped<IAuthorizationHandler, RoleModuleHandler>();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

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

        app.UseRouting();

        app.UseAuthorization();
        app.MapRazorPages();
        app.MapControllerRoute(
            name: "default",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        app.MapControllerRoute(
            name: "root",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        app.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

        app.Run();
    }

}