"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LinkProviderAdapter = void 0;
const tslib_1 = require("tslib");
const ide_core_common_1 = require("@opensumi/ide-core-common");
const Converter = tslib_1.__importStar(require("../../../../common/vscode/converter"));
class LinkProviderAdapter {
    constructor(provider, documents) {
        this.provider = provider;
        this.documents = documents;
        this.cache = new ide_core_common_1.Cache('DocumentLink');
    }
    provideLinks(resource, token) {
        const document = this.documents.getDocumentData(resource);
        if (!document) {
            return Promise.reject(new Error(`There is no document for ${resource}`));
        }
        const doc = document.document;
        return Promise.resolve(this.provider.provideDocumentLinks(doc, token)).then((links) => {
            if (!Array.isArray(links)) {
                return undefined;
            }
            if (typeof this.provider.resolveDocumentLink !== 'function') {
                return { links: links.map(Converter.fromDocumentLink) };
            }
            const pid = this.cache.add(links);
            const result = {
                id: pid,
                links: [],
            };
            for (let i = 0; i < links.length; i++) {
                const data = Converter.fromDocumentLink(links[i]);
                data.cacheId = [pid, i];
                result.links.push(data);
            }
            return result;
        });
    }
    resolveLink(id, token) {
        if (typeof this.provider.resolveDocumentLink !== 'function') {
            return Promise.resolve(undefined);
        }
        const item = this.cache.get(...id);
        if (!item) {
            return Promise.resolve(undefined);
        }
        return Promise.resolve(this.provider.resolveDocumentLink(item, token)).then((value) => {
            if (value) {
                return Converter.fromDocumentLink(value);
            }
            return undefined;
        });
    }
    releaseLink(cacheId) {
        this.cache.delete(cacheId);
    }
}
exports.LinkProviderAdapter = LinkProviderAdapter;
//# sourceMappingURL=link-provider.js.map