using bdHerramientaCACOA.dbcontext;
using DinkToPdf;
using DinkToPdf.Contracts;
using HerramientaCASA;
using HerramientaCASA.Components;
using HerramientaCASA.Model;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
using System.Runtime.InteropServices;
using tsUtilidades;

var builder = WebApplication.CreateBuilder(args);



var context = new AssemnlyLoadwkhtmltox();
// ruta a la dll nativa
context.LoadUnmanagedLibrary(
    Path.Combine(Directory.GetCurrentDirectory(), "DinkToPdf", "libs", "win-x64", "libwkhtmltox.dll")
);

builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
builder.Services.AddScoped<ServicioPDF>();

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

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("es-ES");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("es-ES");

builder.Services.AddRazorPages()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
    });


// Necesario para ver porqué está fallando ciertas cosas que dan el error Circuit
builder.Services.AddServerSideBlazor().AddCircuitOptions(option => { option.DetailedErrors = true; });
builder.Services.AddHttpContextAccessor();
builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(1);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});
builder.Services.AddHttpClient();
builder.Services.AddBlazorBootstrap();
builder.Services.AddAntiforgery();
builder.Services.AddSingleton<UserState>();
builder.Services.AddScoped<ProtectedLocalStorage>();

var app = builder.Build();

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

// Inicializar las cadenas de conexión
var connectionStrings = builder.Configuration.GetSection("ConnectionStrings");
var writeConnectionString = connectionStrings["WriteConnection"];
var readOnlyConnectionString = connectionStrings["ReadOnlyConnection"];

if (string.IsNullOrEmpty(writeConnectionString) || string.IsNullOrEmpty(readOnlyConnectionString))
{
    throw new ArgumentNullException("Las cadenas de conexión no están configuradas correctamente.");
}

tsHerramientasCACOA.EstableceCBD(writeConnectionString, readOnlyConnectionString);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();

app.UseAntiforgery();

app.Use(async (context, next) =>
{
    var userState = context.RequestServices.GetService<UserState>();
    var path = context.Request.Path;

    if (path == "/" ||
        path.StartsWithSegments("/_blazor") ||
        path.StartsWithSegments("/Content") ||
        path.StartsWithSegments("/Scripts") ||
        path.StartsWithSegments("/favicon.ico") ||
        path.StartsWithSegments("/_framework"))
    {
        await next();
        return;
    }

    //// Redirigir al home si no hay token y la ruta no es pública
    //if (userState?.idUser == 0)
    //{
    //    Console.WriteLine($"Redirigiendo al home desde: {path}");
    //    context.Response.Redirect("/");
    //    return;
    //}

    // Continuar con la solicitud
    await next();
});


app.MapGet("/HeaderPdf", () =>
{
    //var bd = tsHerramientasCACOA.NuevoContexto(SoloLectura: true);

    //var logoByte = bd.ficheros
    //    .FirstOrDefault(x => x.NombreFichero == "LogoColegio2")
    //    .Fichero;

    //var logoBase64 = Convert.ToBase64String(logoByte);

    string html = $"<!DOCTYPE html>\r\n" +
                $"<html>\r\n" +
                    $"<head>\r\n" +
                        $"<meta charset='utf-8' />\r\n" +
                        $"<title></title>\r\n" +
                    $"</head>\r\n" +
                    $"<body style='margin:0px !important;'>\r\n" +
                        $"<div style='height:55px; width:100%; font-size:12px; color:#078b98; font-weight:bold; background-color: #D7ECEF; display:flex;'>\r\n" +
                            $"<table style='width:100%; border:0; border-collapse:collapse;'>\r\n" +
                                $" <tr>\r\n" +
                                    $"<td style='text-align: left; width: 50%; padding-left: 10px; padding-top:8px;'>\r\n" +
                                        //$"<img style='height: 40px; border-radius: 10px !important;' src='data:image/jpeg;base64,{logoBase64}' alt='Image'>\r\n" +
                                    $"</td>\r\n" +
                                    $"<td style='text-align: right; width: 50%; padding: 10px;'>\r\n" +
                                        $"Costes Asociados a los Servicios de Arquitectura - CASA\r\n" +
                                    $"</td>\r\n" +
                                $"</tr>\r\n" +
                            $"</table>\r\n" +
                       $"</div>\r\n" +
                    $"</body>\r\n" +
                $"</html>";

    return Results.Content(html, "text/html");
});


app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();
