@page "/Ficheros"
@using System.Net.Http.Headers
@using System.Linq.Expressions
@using Layout
@using Microsoft.AspNetCore
@using Microsoft.AspNetCore.WebUtilities
@using Newtonsoft.Json
@using System.Text
@using Serialize.Linq.Serializers
@using RegistroPersonalAN.Models
@using BlazorBootstrap
@using bdAntifraude.db
@using bdAntifraude.clases
@rendermode InteractiveServer
@layout MainLayout
@inject IHttpClientFactory HttpClientFactory
@inject IHttpContextAccessor HttpContextAccessor
@inject UserState UserState
@inject NavigationManager Navigation
@inject IJSRuntime JS

<div id="cargando" class="loadingFrame" style="background-color:black !important">
    <div class="loadingImg"></div>
</div>

@code{


    private string? tip { get; set; }
    private string? id { get; set; }
    private string? u { get; set; }
    private string? m { get; set; }
    private string? t1 { get; set; }
    private string? t2 { get; set; }
    private string? fe { get; set; }
    private string? o { get; set; }
    private string? fef { get; set; }
    private string? fef2 { get; set; }
    private string? p { get; set; }
    string base64pdf { get; set; } = "";
    private bool shouldOpenPdf;

    private HttpClient client { get; set; } = new HttpClient();
    private ExpressionSerializer serializer { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var token = UserState.Token;
        client = HttpClientFactory.CreateClient();
        client.BaseAddress = new Uri(Utilidades.urlSwagger());
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        serializer = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer());


        var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("tip", out var V1)){tip = V1;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("id", out var V2)){id = V2;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("u", out var V3)){u = V3;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("m", out var V4)){m = V4;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("t1", out var V5)){t1 = V5;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("t2", out var V6)){t2 = V6;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("fe", out var V7)){fe = V7;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("o", out var V8)){o = V8;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("fef", out var V9)){fef = V9;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("fef2", out var V10)){fef2 = V10;}
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("p", out var V11)){p = V11;}

        if (tip == "ha")
        {
            if (u is not null)
            {
                PERSONAS persona = await Utilidades.ObtenerObjeto<PERSONAS>(client, "/api/PERSONAS/" + u);

            }



        }
        else if (tip == "va"){}
        else if (tip == "VerLVA")
        {
            if (id is not null){
                LINEASVIDAADMINISTRATIVA linVi = await Utilidades.ObtenerObjeto<LINEASVIDAADMINISTRATIVA>(client, "/api/LINEASVIDAADMINISTRATIVA/" + id);
                string url = "/api/Almacenamiento/obtener-fichero/";
                PeticionFichero solicitud = new PeticionFichero(linVi.IDLINEAVIDAADMIN, "LINEAVIDAADMINISTRATIVA", linVi?.IDVIDAADMINNavigation?.IDPERSONALNavigation?.NIF!);

                var jsonContent = JsonConvert.SerializeObject(solicitud);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var jsonConsulta = await client.PostAsync(url, content);
                var resultContent = await jsonConsulta.Content.ReadAsStringAsync();
                ResultadoObtenFicheroAtransmitir resultado =  JsonConvert.DeserializeObject<ResultadoObtenFicheroAtransmitir>(resultContent) ?? new ResultadoObtenFicheroAtransmitir();

                base64pdf = Convert.ToBase64String(resultado.Pdf);

                // string urlpdf = "data:application/pdf;base64," + base64pdf;
                // Navigation.NavigateTo(urlpdf, forceLoad: true);

                base64pdf = Convert.ToBase64String(resultado.Pdf); 
                shouldOpenPdf = true;

            }
            // var PueCont = await Pueresponse.Content.ReadAsStringAsync();
        }
        else if (tip == "VerFrm")
        {
            if(id is not null)
            {
                FORMACION formacion = await Utilidades.ObtenerObjeto<FORMACION>(client, "/api/FORMACION/" + id);
                string url = "/api/Almacenamiento/obtener-fichero/";
                PeticionFichero solicitud = new PeticionFichero(formacion.IDFORMACION, "FORMACION", formacion?.IDPERSONANavigation?.NIF!);
                var jsonContent = JsonConvert.SerializeObject(solicitud);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var jsonConsulta = await client.PostAsync(url, content);
                var resultContent = await jsonConsulta.Content.ReadAsStringAsync();
                ResultadoObtenFicheroAtransmitir resultado = JsonConvert.DeserializeObject<ResultadoObtenFicheroAtransmitir>(resultContent) ?? new ResultadoObtenFicheroAtransmitir();                        
                base64pdf = Convert.ToBase64String(resultado.Pdf);
                
                shouldOpenPdf = true;

            }

        }
        else if (tip == "VerDcn")
        {
            if (id is not null)
            {
                DOCENCIA formacion = await Utilidades.ObtenerObjeto<DOCENCIA>(client, "/api/DOCENCIA/" + id);
                string url = "/api/Almacenamiento/obtener-fichero/";
                PeticionFichero solicitud = new PeticionFichero(formacion.IDDOCENCIA, "DOCENCIA", formacion?.IDPERSONANavigation?.NIF!);
                var jsonContent = JsonConvert.SerializeObject(solicitud);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var jsonConsulta = await client.PostAsync(url, content);
                var resultContent = await jsonConsulta.Content.ReadAsStringAsync();
                ResultadoObtenFicheroAtransmitir resultado = JsonConvert.DeserializeObject<ResultadoObtenFicheroAtransmitir>(resultContent) ?? new ResultadoObtenFicheroAtransmitir();
                base64pdf = Convert.ToBase64String(resultado.Pdf);

                shouldOpenPdf = true;

            }

        }
        else if (tip == "VerTit")
        {
            
            if (id is not null)
            {
                TITULACIONES titulacion= await Utilidades.ObtenerObjeto<TITULACIONES>(client, "/api/TITULACIONES/" + id);
                string url = "/api/Almacenamiento/obtener-fichero/";
                PeticionFichero solicitud = new PeticionFichero(titulacion.IDTITULACION, "TITULACION", titulacion?.IDPERSONANavigation?.NIF!);
                var jsonContent = JsonConvert.SerializeObject(solicitud);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                var jsonConsulta = await client.PostAsync(url, content);
                var resultContent = await jsonConsulta.Content.ReadAsStringAsync();
                ResultadoObtenFicheroAtransmitir resultado = JsonConvert.DeserializeObject<ResultadoObtenFicheroAtransmitir>(resultContent) ?? new ResultadoObtenFicheroAtransmitir();
                base64pdf = Convert.ToBase64String(resultado.Pdf);
                shouldOpenPdf = true;
            }
        }
        else if (tip == "lf"){}
        else if (tip == "tp"){}
        else if (tip == "ct"){}
        else if (tip == "st"){}
        else if (tip == "co"){}
        else if (tip == "acju"){}
        else if (tip == "acba"){}
        else if (tip == "acce"){}
        else if (tip == "congrado"){}
        else if (tip == "crpt"){}
        else if (tip == "plapre"){}
    }
    protected  void EnviarArchivo(byte archivo, string Nombre) {
        if (Nombre.ToLower().Contains(".xls"))
        {
            
        }


    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (shouldOpenPdf)
        {
            await JS.InvokeVoidAsync("downloadFile", base64pdf, id + ".pdf");
            await JS.InvokeVoidAsync("openPdfInNewTab", base64pdf); 
            shouldOpenPdf = false;
        }
    }

}

<script>
    function openPdfInNewTab(base64Pdf) {        
        document.getElementsByTagName("html")[0].innerHTML = "<head><title>PDF</title></head><body style='margin:0'><embed style=\"width: 100%;height: 100vh;\" src='data:application/pdf;base64," + base64Pdf + "'></embed></body>"
    }

    function downloadFile(base64Data, fileName) {
        const link = document.createElement("a");
        link.href = `data:application/pdf;base64,${base64Data}`;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
