"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CpdWrapperInvoker = void 0;
const code_analyzer_engine_api_1 = require("@salesforce/code-analyzer-engine-api");
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = __importDefault(require("node:fs"));
const CPD_WRAPPER_JAVA_CLASS = "com.salesforce.sfca.cpdwrapper.CpdWrapper";
const CPD_WRAPPER_LIB_FOLDER = node_path_1.default.resolve(__dirname, '..', 'dist', 'java-lib');
const STDOUT_PROGRESS_MARKER = '[Progress]';
class CpdWrapperInvoker {
    javaCommandExecutor;
    emitLogEvent;
    constructor(javaCommandExecutor, emitLogEvent) {
        this.javaCommandExecutor = javaCommandExecutor;
        this.emitLogEvent = emitLogEvent;
    }
    async invokeRunCommand(inputData, workingFolder, emitProgress) {
        emitProgress(5);
        const inputFile = node_path_1.default.join(workingFolder, 'cpdRunInput.json');
        await node_fs_1.default.promises.writeFile(inputFile, JSON.stringify(inputData), 'utf-8');
        emitProgress(10);
        const outputFile = node_path_1.default.join(workingFolder, 'cpdRunOutput.json');
        const javaCmdArgs = [CPD_WRAPPER_JAVA_CLASS, 'run', inputFile, outputFile];
        const javaClassPaths = [
            node_path_1.default.join(CPD_WRAPPER_LIB_FOLDER, '*'),
        ];
        await this.javaCommandExecutor.exec(javaCmdArgs, javaClassPaths, (stdOutMsg) => {
            if (stdOutMsg.startsWith(STDOUT_PROGRESS_MARKER)) {
                const cpdWrapperProgress = parseFloat(stdOutMsg.slice(STDOUT_PROGRESS_MARKER.length));
                emitProgress(10 + 80 * (cpdWrapperProgress / 100)); // 10 to 90%
            }
            else {
                this.emitLogEvent(code_analyzer_engine_api_1.LogLevel.Fine, `[JAVA StdOut]: ${stdOutMsg}`);
            }
        });
        try {
            const resultsFileContents = await node_fs_1.default.promises.readFile(outputFile, 'utf-8');
            emitProgress(95);
            const cpdResults = JSON.parse(resultsFileContents);
            emitProgress(100);
            return cpdResults;
        }
        catch (err) /* istanbul ignore next */ {
            const errMsg = err instanceof Error ? err.message : String(err);
            throw new Error((0, code_analyzer_engine_api_1.getMessageFromCatalog)(code_analyzer_engine_api_1.SHARED_MESSAGE_CATALOG, 'ErrorParsingOutputFile', outputFile, errMsg), { cause: err });
        }
    }
}
exports.CpdWrapperInvoker = CpdWrapperInvoker;
//# sourceMappingURL=cpd-wrapper.js.map