"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.WorkspaceFolderContext = exports.WorkspaceManager = void 0;
const _ = __importStar(require("lodash"));
const ansibleConfig_1 = require("./ansibleConfig");
const ansibleLint_1 = require("./ansibleLint");
const ansiblePlaybook_1 = require("./ansiblePlaybook");
const docsLibrary_1 = require("./docsLibrary");
const executionEnvironment_1 = require("./executionEnvironment");
const metadataLibrary_1 = require("./metadataLibrary");
const settingsManager_1 = require("./settingsManager");
const path = __importStar(require("path"));
const vscode_uri_1 = require("vscode-uri");
const ansibleInventory_1 = require("./ansibleInventory");
/**
 * Holds the overall context for the whole workspace.
 */
class WorkspaceManager {
    connection;
    sortedWorkspaceFolders = [];
    folderContexts = new Map();
    clientCapabilities = {};
    constructor(connection) {
        this.connection = connection;
    }
    setWorkspaceFolders(workspaceFolders) {
        this.sortedWorkspaceFolders = this.sortWorkspaceFolders(workspaceFolders);
    }
    setCapabilities(capabilities) {
        this.clientCapabilities = capabilities;
    }
    /**
     * Determines the workspace folder context for the given URI.
     */
    getContext(uri) {
        const workspaceFolder = this.getWorkspaceFolder(uri);
        if (workspaceFolder) {
            let context = this.folderContexts.get(workspaceFolder.uri);
            if (!context) {
                context = new WorkspaceFolderContext(this.connection, workspaceFolder, this);
                this.folderContexts.set(workspaceFolder.uri, context);
            }
            return context;
        }
    }
    async forEachContext(callbackfn) {
        await Promise.all(_.map(Array.from(this.folderContexts.values()), (folder) => callbackfn(folder)));
    }
    /**
     * Finds the inner-most workspace folder for the given URI.
     */
    getWorkspaceFolder(uri) {
        for (const workspaceFolder of this.sortedWorkspaceFolders) {
            if (vscode_uri_1.URI.parse(uri).toString().startsWith(workspaceFolder.uri)) {
                return workspaceFolder;
            }
        }
        /* *
         * If control reaches at this point it indicates an individual file is
         * opened in client without any workspace.
         * Set the workspace to directory of the file pointed by uri.
         */
        const documentFolderPathParts = vscode_uri_1.URI.parse(uri).toString().split(path.sep);
        documentFolderPathParts.pop();
        const workspaceFolder = {
            uri: documentFolderPathParts.join(path.sep),
            name: documentFolderPathParts[documentFolderPathParts.length - 1],
        };
        this.connection.console.log(`workspace folder explicitly set to ${vscode_uri_1.URI.parse(workspaceFolder.uri).path}`);
        return workspaceFolder;
    }
    handleWorkspaceChanged(event) {
        const removedUris = new Set(event.removed.map((folder) => folder.uri));
        // We only keep contexts of existing workspace folders
        for (const removedUri of removedUris) {
            this.folderContexts.delete(removedUri);
        }
        const newWorkspaceFolders = this.sortedWorkspaceFolders.filter((folder) => {
            return !removedUris.has(folder.uri);
        });
        newWorkspaceFolders.push(...event.added);
        this.sortedWorkspaceFolders =
            this.sortWorkspaceFolders(newWorkspaceFolders);
    }
    sortWorkspaceFolders(workspaceFolders) {
        return workspaceFolders.sort((a, b) => {
            return b.uri.length - a.uri.length;
        });
    }
}
exports.WorkspaceManager = WorkspaceManager;
/**
 * Holds the context for particular workspace folder. This context is used by
 * all services to interact with the client and with each other.
 */
class WorkspaceFolderContext {
    connection;
    clientCapabilities;
    workspaceFolder;
    documentMetadata;
    documentSettings;
    // Lazy-loading anything that needs this context itself
    _executionEnvironment;
    _docsLibrary;
    _ansibleConfig;
    _ansibleInventory;
    _ansibleLint;
    _ansiblePlaybook;
    constructor(connection, workspaceFolder, workspaceManager) {
        this.connection = connection;
        this.clientCapabilities = workspaceManager.clientCapabilities;
        this.workspaceFolder = workspaceFolder;
        this.documentMetadata = new metadataLibrary_1.MetadataLibrary(connection);
        this.documentSettings = new settingsManager_1.SettingsManager(connection, !!this.clientCapabilities.workspace?.configuration);
        this.documentSettings.onConfigurationChanged(this.workspaceFolder.uri, () => {
            // in case the configuration changes for this folder, we should
            // invalidate the services that rely on it in initialization
            this._executionEnvironment = undefined;
            this._ansibleConfig = undefined;
            this._docsLibrary = undefined;
            this._ansibleInventory = undefined;
        });
    }
    handleWatchedDocumentChange(params) {
        this.documentMetadata.handleWatchedDocumentChange(params);
        for (const fileEvent of params.changes) {
            if (fileEvent.uri.startsWith(this.workspaceFolder.uri)) {
                // in case the configuration changes for this folder, we should
                // invalidate the services that rely on it in initialization
                this._executionEnvironment = undefined;
                this._ansibleConfig = undefined;
                this._docsLibrary = undefined;
            }
        }
    }
    get docsLibrary() {
        if (!this._docsLibrary) {
            const docsLibrary = new docsLibrary_1.DocsLibrary(this.connection, this);
            this._docsLibrary = docsLibrary.initialize().then(() => docsLibrary);
        }
        return this._docsLibrary;
    }
    get ansibleConfig() {
        if (!this._ansibleConfig) {
            const ansibleConfig = new ansibleConfig_1.AnsibleConfig(this.connection, this);
            this._ansibleConfig = ansibleConfig
                .initialize()
                .then(() => ansibleConfig);
        }
        return this._ansibleConfig;
    }
    get ansibleInventory() {
        if (!this._ansibleInventory) {
            const ansibleInventory = new ansibleInventory_1.AnsibleInventory(this.connection, this);
            this._ansibleInventory = ansibleInventory
                .initialize()
                .then(() => ansibleInventory);
        }
        return this._ansibleInventory;
    }
    clearAnsibleInventory() {
        this._ansibleInventory = undefined;
    }
    get ansibleLint() {
        if (!this._ansibleLint) {
            this._ansibleLint = new ansibleLint_1.AnsibleLint(this.connection, this);
        }
        return this._ansibleLint;
    }
    get ansiblePlaybook() {
        if (!this._ansiblePlaybook) {
            this._ansiblePlaybook = new ansiblePlaybook_1.AnsiblePlaybook(this.connection, this);
        }
        return this._ansiblePlaybook;
    }
    get executionEnvironment() {
        if (!this._executionEnvironment) {
            const executionEnvironment = new executionEnvironment_1.ExecutionEnvironment(this.connection, this);
            this._executionEnvironment = executionEnvironment
                .initialize()
                .then(() => executionEnvironment);
        }
        return this._executionEnvironment;
    }
}
exports.WorkspaceFolderContext = WorkspaceFolderContext;
