/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
import { Utils } from './util/vscodeUri.js';
import { defaultMarkdownFileExtension } from './config.js';
export function isWorkspaceWithFileWatching(workspace) {
    return 'watchFile' in workspace;
}
export function getWorkspaceFolder(workspace, docUri) {
    if (workspace.workspaceFolders.length === 0) {
        return undefined;
    }
    // Find the longest match
    const possibleWorkspaces = workspace.workspaceFolders
        .filter(folder => folder.scheme === docUri.scheme
        && folder.authority === docUri.authority
        && (docUri.fsPath.startsWith(folder.fsPath + '/') || docUri.fsPath.startsWith(folder.fsPath + '\\')))
        .sort((a, b) => b.fsPath.length - a.fsPath.length);
    if (possibleWorkspaces.length) {
        return possibleWorkspaces[0];
    }
    // Default to first workspace
    // TODO: Does this make sense?
    return workspace.workspaceFolders[0];
}
export async function openLinkToMarkdownFile(config, workspace, resource) {
    try {
        const doc = await workspace.openMarkdownDocument(resource);
        if (doc) {
            return doc;
        }
    }
    catch {
        // Noop
    }
    const dotMdResource = tryAppendMarkdownFileExtension(config, resource);
    if (dotMdResource) {
        return workspace.openMarkdownDocument(dotMdResource);
    }
    return undefined;
}
/**
 * Check that a link to a file exists.
 *
 * @returns The resolved URI or `undefined` if the file does not exist.
 */
export async function statLinkToMarkdownFile(config, workspace, linkUri, out_statCache) {
    const exists = async (uri) => {
        const result = await workspace.stat(uri);
        out_statCache?.set(uri, { exists: !!result });
        return !!result;
    };
    if (await exists(linkUri)) {
        return linkUri;
    }
    // We don't think the file exists. See if we need to append `.md`
    const dotMdResource = tryAppendMarkdownFileExtension(config, linkUri);
    if (dotMdResource && await exists(dotMdResource)) {
        return dotMdResource;
    }
    return undefined;
}
export function tryAppendMarkdownFileExtension(config, linkUri) {
    const ext = Utils.extname(linkUri).toLowerCase().replace(/^\./, '');
    if (config.markdownFileExtensions.includes(ext)) {
        return linkUri;
    }
    if (ext === '' || !config.knownLinkedToFileExtensions.includes(ext)) {
        return linkUri.with({ path: linkUri.path + '.' + (config.markdownFileExtensions[0] ?? defaultMarkdownFileExtension) });
    }
    return undefined;
}
//# sourceMappingURL=workspace.js.map