$(async function () {

    CargarTabla([]);
    await GetLocation();
    await CargarContrato();

    $("#btnVerify").on("click", function (e) {
        ShowVerify();
    });

    $("#btnSign").on("click", function (e) {
        ShowSign();
    });

    $("#btnConfirm").on("click", function (e) {
        SignContract();
    });

});


var geo = {
    city: "",
    country : "", 
    state: "", 
    ip: "", 
};


async function GetLocation() {
    try{
        var data = await getData("http://ip-api.com/json");
        geo.city = data.city;
        geo.country = data.countryCode == "US" ? "USA" : data.countryCode;
        geo.state = data.region;
        geo.ip = data.query;
    }
    catch(err){
        console.log("Error to obtain geo location");
    }    
}


function getParameterByName(name) {
    name = name.replace(/[\[\]]/g, "\\$&");
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}


async function CargarContrato() {

    var code = getParameterByName("code");

    if (code == null) {
        MensajeError("Input code");
        return;
    }

    var result = await getData("/public/code/" + code);

    if (result.error) {
        MensajeError(result.error);
        return;
    }

    var contract = result.codigo + " - " + result.referencia;
    var company = result.empresa;
    var responsible = result.responsable;
    var email = result.email;

    $("#hfId").val(result.id_contrato);
    $("#lblContract").text(contract);
    $("#lblCompany").text(company);
    $("#lblResponsible").text(responsible);
    $("#lblEmail").text(email);

    await CargarRegistros();
}


async function CargarRegistros() {

    var id = $("#hfId").val();

    if (id == "")
        return;

    try {
        $("#divLoading").show();
        var result = await getData("/public/" + id);
        $("#divLoading").hide();

        if (result.error) {
            MensajeError(result.error);
            return;
        }

        registros = result;
        CargarTabla(registros);

        let lastIndex = registros.length - 1;
        let dto2 = registros[lastIndex];
        dto2.id_estatus == 2 ? $("#divBotones").show() : $("#divBotones").hide();
    }
    catch (err) {
        MensajeError(err.message);
    }
}


function CargarTabla(dataSet) {
    var t = $('#tbRegistros').DataTable({
        data: dataSet,
        pageLength: 5,
        bLengthChange: false,
        ordering: true,
        destroy: true,
        bPaginate: true,
        bFilter: true,
        //bServerSide: false,
        searching: true,
        autoWidth: false,
        info: true,
        aoColumns: [
            { mData: "id_transaccion" },
            { mData: "estatus" },
            { mData: "createdAt" },
        ],
        aoColumnDefs: [
        ],
        order: [[0, 'desc']], // Esto establecerá el orden inicial en la primera columna (cambiar el índice según sea necesario) en orden descendente
    });

    t.on('order.dt search.dt', function () {
        t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
            cell.innerHTML = i + 1;
        });
    }).draw();
}



async function ShowVerify() {

    $("#divLoading").show();
    var result = await postData("/public/verify");
    $("#divLoading").hide();

    if (result.error) {
        MensajeError(result.error);
        return;
    }

    if (result.base64 == "") {
        MensajeError("Template could not be opened");
        return;
    }

    MostrarVisor(result.base64);

    $("#pdf-viewer").html("");
    $('#pdfModal').show().scrollTop(0);

    $("#spTituloPdf").text("PDF Viewer: " + "template-contract.pdf");
    $('#pdfModal').modal('show');
}


async function ShowSign() {

    $("#txtCompany").val("");
    $("#txtAddress").val("");
    $("#txtName").val("");
    $("#txtPosition").val("");
    $("#txtId").val("");

    $('#spTitulo').text('Sign Contract');
    $('#procesoModal').modal('show');
}



function Base64ToUint8Array(base64) {
    const binaryString = atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes;
}


function MostrarVisor(base64String) {

    const pdfData = Base64ToUint8Array(base64String);

    const pdfjsLib = window['pdfjs-dist/build/pdf'];
    pdfjsLib.GlobalWorkerOptions.workerSrc = './pdf/pdf.worker.min.js';

    const pdfViewer = document.getElementById('pdf-viewer');

    function renderPage(page) {
        const viewport = page.getViewport({ scale: 1.5 });
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        pdfViewer.appendChild(canvas);

        const renderContext = {
            canvasContext: context,
            viewport: viewport
        };

        page.render(renderContext);
    }

    const loadingTask = pdfjsLib.getDocument({ data: pdfData });

    loadingTask.promise.then(pdf => {
        for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
            pdf.getPage(pageNum).then(renderPage);
        }
    }).catch(error => {
        console.error('Error PDF Viewer:', error);
    });

}



async function SignContract() {

    var id_contract = parseInt($("#hfId").val());
    var company = $("#txtCompany").val().trim();
    var address = $("#txtAddress").val().trim();
    var name = $("#txtName").val().trim();
    var position = $("#txtPosition").val().trim();
    var id = $("#txtId").val().trim();

    if (company == "") {
        MensajeError("input Company's Name");
        return;
    }

    if (address == "") {
        MensajeError("input Company's Address");
        return;
    }

    if (name == "") {
        MensajeError("input Name of Responsible Person");
        return;
    }

    if (position == "") {
        MensajeError("input Responsible Person's Position");
        return;
    }

    if (id == "" || id.length != 4) {
        MensajeError("input Last 4 Digits of Responsible Person's ID for Electronic Signature");
        return;
    }

    var dto = { id_contrato: id_contract, company, address, name, position, id, city: geo.city, country: geo.country, state: geo.state, ip: geo.ip };

    $("#divLoading").show();
    let result = await postData("/public/sign", dto);
    $("#divLoading").hide();

    if (result.error) {
        MensajeError(result.error);
        return;
    }

    MensajeExitoso("record saved successfully");
    CargarRegistros();

    $('#procesoModal').modal('hide');
}