"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTestValidationManager = exports.createTestWorkspaceManager = exports.smartFilter = exports.isWindows = exports.getDoc = exports.resolveDocUri = exports.disableExecutionEnvironmentSettings = exports.enableExecutionEnvironmentSettings = exports.unsetAnsibleConfigEnv = exports.setAnsibleConfigEnv = exports.unSetFixtureAnsibleCollectionPathEnv = exports.setFixtureAnsibleCollectionPathEnv = exports.ANSIBLE_CONFIG_FILE = exports.ANSIBLE_ADJACENT_COLLECTIONS__PATH = exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH = exports.FIXTURES_BASE_PATH = void 0;
const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
const path = __importStar(require("path"));
const fs_1 = require("fs");
const workspaceManager_1 = require("../src/services/workspaceManager");
const node_1 = require("vscode-languageserver/node");
const validationManager_1 = require("../src/services/validationManager");
const fuse_js_1 = __importDefault(require("fuse.js"));
exports.FIXTURES_BASE_PATH = path.join("test", "fixtures");
exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH = path.resolve(exports.FIXTURES_BASE_PATH, "common", "collections");
exports.ANSIBLE_ADJACENT_COLLECTIONS__PATH = path.resolve("playbook_adjacent_collection", "collections");
exports.ANSIBLE_CONFIG_FILE = path.resolve(exports.FIXTURES_BASE_PATH, "completion", "ansible.cfg");
function setFixtureAnsibleCollectionPathEnv(prePendPath) {
    if (prePendPath) {
        process.env.ANSIBLE_COLLECTIONS_PATHS = `${prePendPath}:${exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH}`;
    }
    else {
        process.env.ANSIBLE_COLLECTIONS_PATHS =
            exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH;
    }
}
exports.setFixtureAnsibleCollectionPathEnv = setFixtureAnsibleCollectionPathEnv;
function unSetFixtureAnsibleCollectionPathEnv() {
    process.env.ANSIBLE_COLLECTIONS_PATHS = undefined;
}
exports.unSetFixtureAnsibleCollectionPathEnv = unSetFixtureAnsibleCollectionPathEnv;
function setAnsibleConfigEnv() {
    process.env.ANSIBLE_CONFIG = exports.ANSIBLE_CONFIG_FILE;
}
exports.setAnsibleConfigEnv = setAnsibleConfigEnv;
function unsetAnsibleConfigEnv() {
    process.env.ANSIBLE_CONFIG = undefined;
}
exports.unsetAnsibleConfigEnv = unsetAnsibleConfigEnv;
async function enableExecutionEnvironmentSettings(docSettings) {
    (await docSettings).executionEnvironment.enabled = true;
    (await docSettings).executionEnvironment.volumeMounts = [
        {
            src: exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH,
            dest: exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH,
            options: undefined,
        },
        {
            src: exports.ANSIBLE_ADJACENT_COLLECTIONS__PATH,
            dest: exports.ANSIBLE_ADJACENT_COLLECTIONS__PATH,
            options: undefined,
        },
    ];
}
exports.enableExecutionEnvironmentSettings = enableExecutionEnvironmentSettings;
async function disableExecutionEnvironmentSettings(docSettings) {
    (await docSettings).executionEnvironment.enabled = false;
}
exports.disableExecutionEnvironmentSettings = disableExecutionEnvironmentSettings;
function resolveDocUri(filename) {
    return path.resolve(exports.FIXTURES_BASE_PATH, filename).toString();
}
exports.resolveDocUri = resolveDocUri;
function getDoc(filename) {
    const file = (0, fs_1.readFileSync)(path.resolve(exports.FIXTURES_BASE_PATH, filename), {
        encoding: "utf8",
    });
    const docUri = path.resolve(exports.FIXTURES_BASE_PATH, filename).toString();
    return vscode_languageserver_textdocument_1.TextDocument.create(docUri, "ansible", 1, file);
}
exports.getDoc = getDoc;
function isWindows() {
    // win32 applies to x64 arch too, is the platform name
    return process.platform === "win32";
}
exports.isWindows = isWindows;
/**
 * A function that tries to imitate the filtering of the completion items done in the respective client extension
 * when the user starts typing against the provided auto-completions
 * @param completionList - list with completion items
 * @param triggerCharacter - string against which fuzzy search is to be done
 * @returns list after sorting and filtering
 */
function smartFilter(completionList, triggerCharacter) {
    if (!completionList) {
        return [];
    }
    // Sort completion list based on `sortText` property of the completion item
    completionList.sort((a, b) => a.sortText && b.sortText ? a.sortText.localeCompare(b?.sortText) : 0);
    // Construct a new Fuse object to do fuzzy search with key as `filterText` property of the completion item
    const searcher = new fuse_js_1.default(completionList, {
        keys: ["filterText"],
        threshold: 0.4,
    });
    let filteredCompletionList = triggerCharacter
        ? searcher
            .search(triggerCharacter)
            .slice(0, 5)
            .map((completion) => {
            return completion.item;
        })
        : completionList.slice(0, 5);
    if (filteredCompletionList.length === 0) {
        // Handle the case when filterText property is not available in completion item.
        // In this case, construct a new Fuse object to do fuzzy search with key as `label` property of the completion item
        const newSearcher = new fuse_js_1.default(completionList, {
            keys: ["label"],
            threshold: 0.2,
        });
        filteredCompletionList = triggerCharacter
            ? newSearcher
                .search(triggerCharacter)
                .slice(0, 5)
                .map((completion) => {
                return completion.item;
            })
            : completionList.slice(0, 5);
    }
    return filteredCompletionList;
}
exports.smartFilter = smartFilter;
/**
 * A function that initiates the connection object with ipc that can be used to create a workspace manager for testing purposes
 * @returns WorkspaceManager - object to serve as a workspace manager for testing purposes
 */
function createTestWorkspaceManager() {
    process.argv.push("--node-ipc");
    const connection = (0, node_1.createConnection)();
    const workspaceManager = new workspaceManager_1.WorkspaceManager(connection);
    workspaceManager.clientCapabilities.window = {
        showMessage: { messageActionItem: { additionalPropertiesSupport: false } },
        showDocument: { support: true },
        workDoneProgress: true,
    };
    connection.listen();
    return workspaceManager;
}
exports.createTestWorkspaceManager = createTestWorkspaceManager;
function createTestValidationManager() {
    process.argv.push("--node-ipc");
    const connection = (0, node_1.createConnection)();
    const documents = new node_1.TextDocuments(vscode_languageserver_textdocument_1.TextDocument);
    const validationManager = new validationManager_1.ValidationManager(connection, documents);
    connection.listen();
    return validationManager;
}
exports.createTestValidationManager = createTestValidationManager;
