import { parseCellAddress } from '@bilig/formula';
export function shouldRefreshPivotSource(pivot, changed, workbook) {
    if (!pivot.source || pivot.cacheOnly) {
        return false;
    }
    const ownerSheet = workbook.getSheet(pivot.source.sheetName);
    if (!ownerSheet) {
        return true;
    }
    const ownerStart = parseCellAddress(pivot.source.startAddress, pivot.source.sheetName);
    const ownerEnd = parseCellAddress(pivot.source.endAddress, pivot.source.sheetName);
    for (let index = 0; index < changed.length; index += 1) {
        const cellIndex = changed[index];
        const sheetId = workbook.cellStore.sheetIds[cellIndex];
        if (sheetId === undefined || sheetId !== ownerSheet.id) {
            continue;
        }
        const position = workbook.getCellPosition(cellIndex);
        const row = position?.row ?? workbook.cellStore.rows[cellIndex] ?? -1;
        const col = position?.col ?? workbook.cellStore.cols[cellIndex] ?? -1;
        if (row >= ownerStart.row && row <= ownerEnd.row && col >= ownerStart.col && col <= ownerEnd.col) {
            return true;
        }
    }
    return false;
}
export function refreshPivotOutputsForChangedCells(input) {
    const pivots = input.workbook.listPivots();
    if (pivots.length === 0 || (!input.forceAll && input.changed.length === 0)) {
        return input.emptyChangedSet();
    }
    const changedCellIndices = [];
    const changedSeen = new Set();
    for (let index = 0; index < pivots.length; index += 1) {
        const pivot = pivots[index];
        if (!input.forceAll && !shouldRefreshPivotSource(pivot, input.changed, input.workbook)) {
            continue;
        }
        const pivotChanges = input.materializePivot(pivot);
        for (let changeIndex = 0; changeIndex < pivotChanges.length; changeIndex += 1) {
            const cellIndex = pivotChanges[changeIndex];
            if (!changedSeen.has(cellIndex)) {
                changedSeen.add(cellIndex);
                changedCellIndices.push(cellIndex);
            }
        }
    }
    return changedCellIndices.length === 0 ? input.emptyChangedSet() : Uint32Array.from(changedCellIndices);
}
//# sourceMappingURL=recalc-pivot-refresh.js.map