"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeHierarchyAdapter = void 0;
const tslib_1 = require("tslib");
const id_generator_1 = require("@opensumi/ide-core-common/lib/id-generator");
const Converter = tslib_1.__importStar(require("../../../../common/vscode/converter"));
class TypeHierarchyAdapter {
    constructor(_documents, _provider) {
        this._documents = _documents;
        this._provider = _provider;
        this._idPool = new id_generator_1.IdGenerator('');
        this._cache = new Map();
    }
    async prepareSession(uri, position, token) {
        const documentData = this._documents.getDocumentData(uri);
        if (!documentData) {
            return Promise.reject(new Error(`There is no document for ${uri}`));
        }
        const doc = documentData.document;
        const pos = Converter.Position.to(position);
        const items = await this._provider.prepareTypeHierarchy(doc, pos, token);
        if (!items) {
            return undefined;
        }
        const sessionId = this._idPool.nextId();
        this._cache.set(sessionId, new Map());
        if (Array.isArray(items)) {
            return items.map((item) => this._cacheAndConvertItem(sessionId, item));
        }
        else {
            return [this._cacheAndConvertItem(sessionId, items)];
        }
    }
    async provideSupertypes(sessionId, itemId, token) {
        const item = this._itemFromCache(sessionId, itemId);
        if (!item) {
            throw new Error('missing type hierarchy item');
        }
        const supertypes = await this._provider.provideTypeHierarchySupertypes(item, token);
        if (!supertypes) {
            return undefined;
        }
        return supertypes.map((supertype) => this._cacheAndConvertItem(sessionId, supertype));
    }
    async provideSubtypes(sessionId, itemId, token) {
        const item = this._itemFromCache(sessionId, itemId);
        if (!item) {
            throw new Error('missing type hierarchy item');
        }
        const subtypes = await this._provider.provideTypeHierarchySubtypes(item, token);
        if (!subtypes) {
            return undefined;
        }
        return subtypes.map((subtype) => this._cacheAndConvertItem(sessionId, subtype));
    }
    releaseSession(sessionId) {
        this._cache.delete(sessionId);
    }
    _cacheAndConvertItem(sessionId, item) {
        const map = this._cache.get(sessionId);
        const dto = Converter.TypeHierarchyItem.from(item, sessionId, map.size.toString(36));
        map.set(dto._itemId, item);
        return dto;
    }
    _itemFromCache(sessionId, itemId) {
        const map = this._cache.get(sessionId);
        return map === null || map === void 0 ? void 0 : map.get(itemId);
    }
}
exports.TypeHierarchyAdapter = TypeHierarchyAdapter;
//# sourceMappingURL=type-hierarchy.js.map