// JavaScript Document

console.log("LIBRARY: libPDFscripts.js")
//Use this function as a start - to pass the path, then datasource to update with pdfbytes, then download -- Maybe combine into one file?
//wich is more efficient?

let popover = new bootstrap.Popover(popoverTrigger, {
    content: "This dropdown is disabled.",
    placement: "top",
    trigger: "manual"
});

//filepath = /PDF/XXX.pdf, dataSource = datastore.var
// *** Use of 'rest paramater' syntax to add extra datasources at the end.
//return array of datasources i.e [datastore,data_view1] and pass that array to  updatePdfFields
//Consider default values = filepath = '/PDF/masterTemplate.pdf'
async function toBase64(filePath, ...dataSources) {
    console.log(filePath);
    const pdfBytes = await fetch(filePath).then((res) => res.arrayBuffer());

    // console.log(dataSources); // should be only 2,
    updatePdfFields(pdfBytes, dataSources);

    //return pdfBytes
}

async function updatePdfFields(pdfBytes, dataSources) {
    // Load the PDF document
    console.log("pdfBytes.size =", pdfBytes.byteLength);
    console.log(dataSources);
    const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
    const form = pdfDoc.getForm();

    // Loop over each data source passed to the function
    dataSources.forEach((dataSource) => {
        // Loop over each record in the current data source
        dataSource.forEach((record) => {
            // Loop over each key-value pair in the record
            Object.entries(record).forEach(([fieldName, fieldValue]) => {
                console.log(fieldName, " => ", fieldValue);

                // Find the form field in the PDF by name
                /** !!! BLOCK 1 Start                
                            const formField = form.getTextField(fieldName);
                            // If the field exists in the PDF, update it with the value
                            if (formField) {
                                formField.setText(String(fieldValue));
                            }
                        **/ // BLOCK 1 END
            });
        });
    });

    // Serialize the PDF back to bytes
    const updatedPdfBytes = await pdfDoc.save();

    // Trigger download of the updated PDF
    downloadPdf(updatedPdfBytes, "UpdatedDocument.pdf");
}

// Function to trigger download of the updated PDF
function downloadPdf(pdfBytes, fileName) {
    // Create a Blob from the PDF bytes
    const blob = new Blob([pdfBytes], { type: "application/pdf" });
    const url = URL.createObjectURL(blob);

    // Create a link element for the download
    const link = document.createElement("a");
    link.href = url;
    link.download = fileName;

    // Append the link to the document, trigger a click, and remove it afterward
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // Release the object URL to free up memory
    URL.revokeObjectURL(url);
}

// Usage Example
async function main() {
    // Load your PDF as bytes (e.g., using fetch)
    const pdfBytes = await fetch("path/to/your.pdf").then((res) =>
        res.arrayBuffer()
    );

    // Sample data sources from Wappler
    const dataSource1 = [{ fieldName1: "Value1", fieldName2: "Value2" }];
    const dataSource2 = [
        { fieldName3: "AnotherValue1", fieldName4: "AnotherValue2" },
    ];

    // Call the function with multiple data sources
    await updatePdfFields(pdfBytes, dataSource1, dataSource2);
}

function generateRandomFilename() {
    const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let filename = "";
    for (let i = 0; i < 8; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        filename += characters[randomIndex];
    }
    console.log("Random Filename: ", filename);
    return filename;
}


