"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectionRangeAdapter = 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"));
const { isNonEmptyArray } = ide_core_common_1.arrays;
class SelectionRangeAdapter {
    constructor(documents, _provider) {
        this.documents = documents;
        this._provider = _provider;
    }
    async provideSelectionRanges(resource, pos, token) {
        const documentData = this.documents.getDocumentData(resource);
        if (!documentData) {
            return Promise.reject(new Error(`There is no document for ${resource}`));
        }
        const doc = documentData.document;
        const zeroBasedPositions = pos.map(Converter.toPosition);
        const allProviderRanges = await this._provider.provideSelectionRanges(doc, zeroBasedPositions, token);
        if (!isNonEmptyArray(allProviderRanges)) {
            return [];
        }
        if (allProviderRanges.length !== zeroBasedPositions.length) {
            // eslint-disable-next-line no-console
            console.warn('BAD selection ranges, provider must return ranges for each position');
            return [];
        }
        const allResults = [];
        for (let i = 0; i < zeroBasedPositions.length; i++) {
            const oneResult = [];
            allResults.push(oneResult);
            let last = zeroBasedPositions[i];
            let selectionRange = allProviderRanges[i];
            while (true) {
                if (!selectionRange.range.contains(last)) {
                    throw new Error('INVALID selection range, must contain the previous range');
                }
                oneResult.push(Converter.fromSelectionRange(selectionRange));
                if (!selectionRange.parent) {
                    break;
                }
                last = selectionRange.range;
                selectionRange = selectionRange.parent;
            }
        }
        return allResults;
    }
}
exports.SelectionRangeAdapter = SelectionRangeAdapter;
//# sourceMappingURL=selection.js.map