import * as monaco from 'monaco-editor';

function getRangesFromDecorations(model, decorationFilter) {
    return model
        .getAllDecorations()
        .filter(decorationFilter)
        .map((decoration) => decoration.range);
}
function excludeRanges(model, uniqueRange, ranges) {
    const filteredRanges = [];
    const removedRanges = [];
    let lastEndPosition = uniqueRange.getStartPosition();
    const uniqueRangeEndPosition = uniqueRange.getEndPosition();
    const intersectingRanges = ranges.filter((range) => monaco.Range.areIntersectingOrTouching(range, uniqueRange));
    for (const range of intersectingRanges) {
        const rangeStart = range.getStartPosition();
        const rangeEnd = range.getEndPosition();
        if (lastEndPosition.isBefore(rangeStart)) {
            const firstRangeStart = lastEndPosition.equals(uniqueRange.getStartPosition())
                ? lastEndPosition
                : model.modifyPosition(lastEndPosition, 1);
            filteredRanges.push(monaco.Range.fromPositions(firstRangeStart, model.modifyPosition(rangeStart, -1)));
        }
        const secondRangeStart = lastEndPosition.isBefore(rangeStart) ? rangeStart : lastEndPosition;
        const secondRangeEnd = uniqueRangeEndPosition.isBefore(rangeEnd)
            ? uniqueRangeEndPosition
            : rangeEnd;
        removedRanges.push(monaco.Range.fromPositions(secondRangeStart, secondRangeEnd));
        lastEndPosition = rangeEnd;
    }
    if (lastEndPosition.isBeforeOrEqual(uniqueRangeEndPosition)) {
        const firstRangeStart = lastEndPosition.equals(uniqueRange.getStartPosition())
            ? lastEndPosition
            : model.modifyPosition(lastEndPosition, 1);
        filteredRanges.push(monaco.Range.fromPositions(firstRangeStart, uniqueRangeEndPosition));
    }
    return { filteredRanges, removedRanges };
}

export { excludeRanges, getRangesFromDecorations };
