"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;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnsibleConfig = void 0;
const ini = __importStar(require("ini"));
const _ = __importStar(require("lodash"));
const path = __importStar(require("path"));
const vscode_uri_1 = require("vscode-uri");
const commandRunner_1 = require("../utils/commandRunner");
class AnsibleConfig {
    constructor(connection, context) {
        this._collection_paths = [];
        this._module_locations = [];
        this._ansible_location = "";
        this._default_host_list = [];
        this._ansible_meta_data = {};
        this.connection = connection;
        this.context = context;
    }
    initialize() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const settings = yield this.context.documentSettings.get(this.context.workspaceFolder.uri);
                const workingDirectory = vscode_uri_1.URI.parse(this.context.workspaceFolder.uri).path;
                const mountPaths = new Set([workingDirectory]);
                const commandRunner = new commandRunner_1.CommandRunner(this.connection, this.context, settings);
                // get Ansible configuration
                const ansibleConfigResult = yield commandRunner.runCommand("ansible-config", "dump", workingDirectory, mountPaths);
                let config = ini.parse(ansibleConfigResult.stdout);
                config = _.mapKeys(config, (_, key) => key.substring(0, key.indexOf("(")));
                if (typeof config.COLLECTIONS_PATHS === "string") {
                    this._collection_paths = parsePythonStringArray(config.COLLECTIONS_PATHS);
                }
                else {
                    this._collection_paths = [];
                }
                // get default host list from config dump
                if (typeof config.DEFAULT_HOST_LIST === "string") {
                    this._default_host_list = parsePythonStringArray(config.DEFAULT_HOST_LIST);
                }
                else {
                    this._default_host_list = [];
                }
                // get Ansible basic information
                const ansibleVersionResult = yield commandRunner.runCommand("ansible", "--version");
                const versionInfo = ini.parse(ansibleVersionResult.stdout);
                this._ansible_meta_data = versionInfo;
                this._module_locations = parsePythonStringArray(versionInfo["configured module search path"]);
                this._module_locations.push(path.resolve(versionInfo["ansible python module location"], "modules"));
                this._ansible_location = versionInfo["ansible python module location"];
                // get Python sys.path
                // this is needed to get the pre-installed collections to work
                const pythonPathResult = yield commandRunner.runCommand("python3", ' -c "import sys; print(sys.path, end=\\"\\")"');
                this._collection_paths.push(...parsePythonStringArray(pythonPathResult.stdout));
            }
            catch (error) {
                if (error instanceof Error) {
                    this.connection.window.showErrorMessage(error.message);
                }
                else {
                    this.connection.console.error(`Exception in AnsibleConfig service: ${JSON.stringify(error)}`);
                }
            }
        });
    }
    set collections_paths(updatedCollectionPath) {
        this._collection_paths = updatedCollectionPath;
    }
    get collections_paths() {
        return this._collection_paths;
    }
    set default_host_list(defaultHostList) {
        this._default_host_list = defaultHostList;
    }
    get default_host_list() {
        return this._default_host_list;
    }
    set module_locations(updatedModulesPath) {
        this._module_locations = updatedModulesPath;
    }
    get module_locations() {
        return this._module_locations;
    }
    get ansible_location() {
        return this._ansible_location;
    }
    get ansible_meta_data() {
        return this._ansible_meta_data;
    }
}
exports.AnsibleConfig = AnsibleConfig;
function parsePythonStringArray(string_list) {
    const cleaned_str = string_list.slice(1, string_list.length - 1); // remove []
    const quoted_elements = cleaned_str.split(",").map((e) => e.trim());
    return quoted_elements.map((e) => e.slice(1, e.length - 1));
}
//# sourceMappingURL=ansibleConfig.js.map