const fs = require('fs');
const path = require('path');
const { XMLParser, XMLBuilder, XMLValidator } = require("fast-xml-parser");
var mysql = require('mysql');
var Stimulsoft = require('stimulsoft-reports-js');
//Stimulsoft.Base.Localization.StiLocalization.addLocalizationFile("../localization/it.xml");
Stimulsoft.Base.StiLicense.Key = "6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHl2rCPWxELIofkY3UYnx7oY+1oDDHrnFg9gbvUjuP8P0f0OWJOyrrUu/OMaviDWSUxpASfBHo6Tz55h05Be2CGchFnf3jE/IpBhZ24RxugUwXpjUK9N6h3SAz29+5Gvq/Uv95dW+jQ4y+agQHDKSZfHXgvnjPX5cI9vbx5TPhTXIk2vAuy5ksH1CzU5UK8MDFw1+YK2SNFzg6t/FmQZ5ktupZtEA7vK1yneS1I8MyLj4Y8ngnhhAvuUzxuN74DLl88amxUK9G0oHKLayKwnkmTaIN8zUyugaqPbUd8EL+898FgajMQFJWjBfCh7sLU6ciDDPr46/XiXjb8N7MMVveM4sfTrQ5K+mY1w0Q5TiYjqm0v/RaMarVS9rvF5ma5coFtWt/r0SgvdmOmtEfMjhWFJ/XGC3hYS8dzGSBh7CIuWyn/mzGC3q/BfrEajJFSl2MR8I63fFIT05VP5tPwpB+8R0OSKrdm49GixTkiW8JSB0pyAeradYSGx35uWKjv5/Ye9efaa32ohX4uCIRAQ5hgk7HvAPbioi/IjJGWdGrcJ1A==";

var report = new Stimulsoft.Report.StiReport();



// dobbiamo prendere in parametro il project + path 
const arguments = process.argv;


//leggo il db
const db_xml = fs.readFileSync(__dirname + '/../config/database_config.xml');
const parser = new XMLParser();
let jObj = parser.parse(db_xml);

var pool = mysql.createPool({
    host: jObj['database-config']['db-ip'],
    user: jObj['database-config'].user,
    password: jObj['database-config'].password,
    database: jObj['database-config']['db-name'],
    port: 3306,
    connectionLimit: 100,
    multipleStatements: true
});


//Apro pool di connessione al db.
pool.getConnection(function (conn_err, db) {

    if (conn_err) {

        console.log(conn_err);
        return "error";

    }

    db.query("SELECT * FROM ze_report_projects WHERE id = ?", [process.argv[2]], (qerr, result) => {

        if (qerr || result.length === 0) {
            process.exit();
        }

        // Loading report template
        report.load(JSON.parse(result[0].payload));

        report.onBeginProcessData = (args) => {
            args.pathData = process.argv[3].replace(/\\/g, '/');
        }


        report.renderAsync(() => {

            console.log("Report rendered. Pages count: ", report.renderedPages.count);


            // Export to PDF
            report.exportDocumentAsync((pdfData) => {



                // Converting Array into buffer
                var buffer = Buffer.from(pdfData);

                // Saving string with rendered report in PDF into a file
                fs.writeFileSync(process.argv[4], buffer);

                console.log("Rendered report saved into PDF-file.");
                process.exit();

            },

                Stimulsoft.Report.StiExportFormat.Pdf);


        });

    })

});