// Developed using the VSC language extension tutorial
// https://code.visualstudio.com/api/language-extensions/overview

const vscode = require('vscode');
const { execSync } = require('child_process');
const { parse } = require('path');

function activate(context) {
    console.log('IntelliWACC is now active!');

    let diagnosticCollection = vscode.languages.createDiagnosticCollection('wacc');
    context.subscriptions.push(diagnosticCollection);

    vscode.workspace.onDidSaveTextDocument((document) => {
        if (document.languageId !== 'wacc') return;

        let diagnostics = [];
        let errors = generateErrors(document.getText(), document.fileName);
        errors.forEach(error => {
            console.log(error);
            let range = new vscode.Range(error.line - 1 , error.column - 1, error.line - 1, error.column + error.size);
            let diagnostic = new vscode.Diagnostic(range, error.errorMessage, vscode.DiagnosticSeverity.Error);
            diagnostics.push(diagnostic);
        });

        diagnosticCollection.set(document.uri, diagnostics);
    });
}

function deactivate() {
    console.log('IntelliWACC is deactivating...');
}

function generateErrors(code, filePath) {
    try {
        console.log("generating errors")
        const fs = require('fs');
        const tmpFilePath = parse(filePath).dir + '/.temp_wacc_file.wacc';
        fs.writeFileSync(tmpFilePath, code);

        let output;
        try {
            const waccExePath = `${__dirname}/wacc-compiler`;
            output = execSync(`${waccExePath} ${tmpFilePath}`, { encoding: 'utf8', shell: true, stdio: 'pipe'});
        } catch (err) {
            console.log("Error running compiler");
            output = err.stdout;
            console.log(output);
        } 
        let errors = [];
        errorRegex = /\(line ([\d]+), column ([\d]+)\):\n([^>]+)([^\^]+)([\^]+)\n([^\n]+)([^\(]*)/g
        while((match = errorRegex.exec(output)) !== null) {
            console.log(match[5]);
            errors.push({
                line: parseInt(match[1], 10),
                column: parseInt(match[2], 10),
                errorMessage: match[3].trim(),
                size: match[5].length - 1
            });
        }
        return errors;
    } catch (err) {
        console.error('Error running compiler:', err);
        return [];
    }
}

module.exports = {
    activate,
    deactivate
};
