const fs = require('fs');
const readline = require('readline');

const INPUT_FILE = `${__dirname}/../SimConnect/inc/SimConnect.h`;
const OUTPUT_DIRECTORY = `${__dirname}/../src/generated/`;
const RELEVANT_ENUMS = ["PERIOD", "SIMOBJECT_TYPE", "DATATYPE"]; // Without the "SIMCONNECT_"-prefix

const inputFile = readline.createInterface({
  input: fs.createReadStream(INPUT_FILE),
  output: process.stdout,
  terminal: false
});

if (!fs.existsSync(OUTPUT_DIRECTORY)){
    fs.mkdirSync(OUTPUT_DIRECTORY, { recursive: true });
}

const ENUM_NAME_REGEX = /enum SIMCONNECT_(\S*) {/gm;
const ENUM_VALUE_REGEX = /^\s*SIMCONNECT_([A-Z0-9_]*)((.*=\s*(.*)\s*),)?/;
const ENUM_END_REGEX = /^\s*};\s*$/;

let valueCounter = 0;
let currentEnumName = undefined;

const outputJson = {};

inputFile.on('line', (line) => {
    const enumNameMatch = ENUM_NAME_REGEX.exec(line);

    if (enumNameMatch) {
        if (!RELEVANT_ENUMS.includes(enumNameMatch[1])) return;
        currentEnumName = enumNameMatch[1];
        outputJson[currentEnumName] = {};
        valueCounter = 0;
    } else if (currentEnumName) {
        if (ENUM_END_REGEX.exec(line)) {
            currentEnumName = undefined;
        } else {
            const nameMatch = ENUM_VALUE_REGEX.exec(line);
            if (nameMatch) {
                const valueName = nameMatch[1].replace(currentEnumName + "_", "");
                const fixedValue = nameMatch[4];
                if (fixedValue) {
                    // Skip ahead and continue incrementing from this value
                    valueCounter = Number.parseInt(fixedValue.trim());
                }
                outputJson[currentEnumName][valueName] = valueCounter;
                valueCounter++;
            }
        }
    }
})

inputFile.on("close", () => {
    const outputFile = fs.createWriteStream(`${OUTPUT_DIRECTORY}/constants.js`);
    outputFile.write(`// Autogenerated file [${new Date().toDateString()}]\r\n`);
    outputFile.write("module.exports = " + JSON.stringify(outputJson, null, 4))
})