/////////////////////////////////////////////////
// LOGGING
/////////////////////////////////////////////////
const logger = require("../public/js/app/logger_concert");

// ADOBE PDF
const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');

////////////////////////////////////////////////////
// CONNECTION ADOBE API
////////////////////////////////////////////////////

async function pdfgo(OUTPUT, INPUT, JSON_INPUT) {
    logger.info("AVANT CREATION DU PDF");

    const credentials =  PDFServicesSdk.Credentials
    .servicePrincipalCredentialsBuilder()
    .withClientId(process.env.PDF_SERVICES_CLIENT_ID)
    .withClientSecret(process.env.PDF_SERVICES_CLIENT_SECRET)
    .build();

    const clientConfig = PDFServicesSdk.ClientConfig
    .clientConfigBuilder()
    .withConnectTimeout(20000)
    .withReadTimeout(40000)
    .build();

    const executionContext = PDFServicesSdk.ExecutionContext.create(credentials);

    const documentMerge = PDFServicesSdk.DocumentMerge,
    documentMergeOptions = documentMerge.options,
    adobe_options = new documentMergeOptions.DocumentMergeOptions(JSON_INPUT, documentMergeOptions.OutputFormat.PDF);
    
    // Create a new operation instance using the options instance.
    const documentMergeOperation = documentMerge.Operation.createNew(adobe_options);
    
    // Set operation input document template from a source file.
    const input = PDFServicesSdk.FileRef.createFromLocalFile(INPUT);
    documentMergeOperation.setInput(input);
    
    // Execute the operation and Save the result to the specified location.
    await documentMergeOperation
    .execute(executionContext)
    .then(result => result.saveAsFile(OUTPUT).then(
    )
    )
    .catch(err => {
        if(err instanceof PDFServicesSdk.Error.ServiceApiError
            || err instanceof PDFServicesSdk.Error.ServiceUsageError) {
            console.log('Exception encountered while executing ADOBE PDF', err);
        } else {
            console.log('Exception encountered while executing ADOBE PDF', err);
        }
    });
    
    logger.info("APRES CREATION DU PDF");

}

module.exports = {
    pdfgo
}