"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.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_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");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Fuse = 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_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;
function enableExecutionEnvironmentSettings(docSettings) {
    return __awaiter(this, void 0, void 0, function* () {
        (yield docSettings).executionEnvironment.enabled = true;
        (yield docSettings).executionEnvironment.volumeMounts = [
            {
                src: exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH,
                dest: exports.ANSIBLE_COLLECTIONS_FIXTURES_BASE_PATH,
                options: undefined,
            },
        ];
    });
}
exports.enableExecutionEnvironmentSettings = enableExecutionEnvironmentSettings;
function disableExecutionEnvironmentSettings(docSettings) {
    return __awaiter(this, void 0, void 0, function* () {
        (yield 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.localeCompare(b.sortText));
    // Construct a new Fuse object to do fuzzy search with key as `filterText` property of the completion item
    const searcher = new Fuse(completionList, {
        keys: ["filterText"],
        threshold: 0.4,
        refIndex: false,
    });
    let filteredCompletionList = triggerCharacter
        ? searcher.search(triggerCharacter).slice(0, 5)
        : 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(completionList, {
            keys: ["label"],
            threshold: 0.2,
            refIndex: false,
        });
        filteredCompletionList = triggerCharacter
            ? newSearcher.search(triggerCharacter).slice(0, 5)
            : 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;
//# sourceMappingURL=helper.js.map