// This script goes into every modules folder and converts
// db_table_config.sql.template into a valid SQL file.

const fs = require("fs");
const cliProgress = require('cli-progress');

// Find all modules
const folderList = fs.readdirSync("apiHandler");
console.log("SQL Minifyer found " + folderList.length + " folders")
const bar1 = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

// Build paths for every module
for(let m = 0; m < folderList.length; m++) {
    folderList[m] = "apiHandler/" + folderList[m] + "/db_table_config.sql.template"
}

bar1.start(folderList.length, 0);

// Go through each module
for(elm in folderList){ 
    const inputTable = fs.readFileSync(folderList[elm]); // Read the template file
    const allLines = String(inputTable).split("\n"); // Split into single elements
    let longStr = "";
    let fileOutput = "";
    for(let i = 0; i < allLines.length; i++){ // Go through all tese lines and make them a single one
        if( ! allLines[i].includes("#NL")){ // #NL sperates quries
            longStr += allLines[i].replace("\r", "").replace("\t", " "); // Remove tabs and carriege returns
        }else{
            fileOutput += longStr + "\n";
            longStr = "";
        }
    }
    fileOutput = fileOutput.substring(0, fileOutput.length - 1);
    bar1.increment()
    fs.writeFileSync(folderList[elm].replace(".template", ""), fileOutput); // Save to path
}
setTimeout(function(){
    bar1.stop();
    console.log("Done.");
}, 200)
