"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnsiblePlaybook = void 0;
const path = __importStar(require("path"));
const vscode_uri_1 = require("vscode-uri");
const vscode_languageserver_1 = require("vscode-languageserver");
const commandRunner_1 = require("../utils/commandRunner");
/**
 * Acts as an interface to ansible-playbook command.
 */
class AnsiblePlaybook {
    connection;
    context;
    useProgressTracker = false;
    /**
     *
     * @param connection - establishes connection with the client
     * @param context - provides workspace context of the client
     */
    constructor(connection, context) {
        this.connection = connection;
        this.context = context;
        this.useProgressTracker =
            !!context.clientCapabilities.window?.workDoneProgress;
    }
    /**
     * Acts as an interface to ansible-playbook <file> --syntax-check command and a cache of its output.
     * ansible syntax-check may provide diagnostics for more than just the file for which
     * it was triggered, and this is reflected in the implementation.
     *
     * Perform ansible syntax-check for the given document.
     */
    async doValidate(textDocument) {
        const docPath = vscode_uri_1.URI.parse(textDocument.uri).path;
        let diagnostics = new Map();
        const progressTracker = this.useProgressTracker
            ? await this.connection.window.createWorkDoneProgress()
            : {
                begin: () => {
                    // do nothing
                },
                done: () => {
                    // do nothing
                },
            };
        const workingDirectory = vscode_uri_1.URI.parse(this.context.workspaceFolder.uri).path;
        const mountPaths = new Set([workingDirectory, path.dirname(docPath)]);
        const settings = await this.context.documentSettings.get(textDocument.uri);
        progressTracker.begin("ansible syntax-check", undefined, "Processing files...");
        const commandRunner = new commandRunner_1.CommandRunner(this.connection, this.context, settings);
        try {
            // run ansible playbook syntax-check
            await commandRunner.runCommand("ansible-playbook", `${docPath} --syntax-check`, workingDirectory, mountPaths);
        }
        catch (error) {
            if (error instanceof Error) {
                const execError = error;
                // This is the regex to extract the filename, line and column number from the stderr produced by syntax-check command
                const ansibleSyntaxCheckRegex = /The error appears to be in '(?<filename>.*)': line (?<line>\d+), column (?<column>\d+)/;
                const filteredErrorMessage = ansibleSyntaxCheckRegex.exec(execError.stderr);
                diagnostics =
                    filteredErrorMessage && filteredErrorMessage.groups
                        ? this.processReport(execError.message, filteredErrorMessage.groups.filename, parseInt(filteredErrorMessage.groups.line), parseInt(filteredErrorMessage.groups.column))
                        : this.processReport(execError.message, docPath, 1, 1);
                if (execError.stderr) {
                    this.connection.console.info(`[ansible syntax-check] ${execError.stderr}`);
                }
            }
            else {
                this.connection.console.error(`Exception in AnsibleSyntaxCheck service: ${JSON.stringify(error)}`);
            }
        }
        progressTracker.done();
        return diagnostics;
    }
    processReport(result, fileName, line, column) {
        const diagnostics = new Map();
        if (!result) {
            this.connection.console.warn("Standard output from ansible syntax-check is suspiciously empty.");
            return diagnostics;
        }
        const start = {
            line: line - 1,
            character: column - 1,
        };
        const end = {
            line: line - 1,
            character: vscode_languageserver_1.integer.MAX_VALUE,
        };
        const range = {
            start,
            end,
        };
        const severity = vscode_languageserver_1.DiagnosticSeverity.Error;
        const locationUri = `file://${fileName}`;
        const fileDiagnostics = diagnostics.get(locationUri) || [];
        fileDiagnostics.push({
            message: result,
            range,
            severity,
            source: "Ansible",
        });
        diagnostics.set(locationUri, fileDiagnostics);
        return diagnostics;
    }
}
exports.AnsiblePlaybook = AnsiblePlaybook;
