"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.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 {
    connection;
    context;
    _collection_paths = [];
    _module_locations = [];
    _ansible_location = "";
    _default_host_list = [];
    _ansible_meta_data = {}; // ini data
    constructor(connection, context) {
        this.connection = connection;
        this.context = context;
    }
    async initialize() {
        try {
            const settings = await 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 = await 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 = await 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 = await 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));
}
