export class CellHighlightManager {
    constructor(sheet) {
        this.highlightedCells = new Map, this.colors = [ "#4A90E2", "#50C878", "#FF6B6B", "#FFD93D", "#6BCB77", "#9B59B6", "#FF8C42", "#00BCD4" ], 
        this.colorIndex = 0, this.sheet = sheet;
    }
    parseCellReferences(formula) {
        const references = [], cellRefRegex = /(?:([']?[^!'\s]+[']?)!)?(\$?[A-Z]+\$?\d+(?::\$?[A-Z]+\$?\d+)?)/g, uniqueRefs = new Map;
        let match;
        for (this.colorIndex = 0; null !== (match = cellRefRegex.exec(formula)); ) {
            const sheetNamePart = match[1], cellRef = match[2];
            let sheetName;
            sheetNamePart && (sheetName = sheetNamePart.replace(/'/g, ""));
            const normalizedCellRef = cellRef.replace(/\$/g, "").toUpperCase(), uniqueKey = sheetName ? `${sheetName}!${normalizedCellRef}` : normalizedCellRef;
            if (!uniqueRefs.has(uniqueKey)) {
                uniqueRefs.set(uniqueKey, {
                    sheetName: sheetName,
                    cellRef: normalizedCellRef
                });
                try {
                    const isRange = normalizedCellRef.includes(":");
                    let coords = [];
                    const targetSheet = sheetName ? this.sheet.getSheetByName(sheetName) : this.sheet.getActiveSheet();
                    if (!targetSheet) continue;
                    if (isRange) coords = this.parseRangeReference(normalizedCellRef, targetSheet); else {
                        coords = [ targetSheet.coordFromAddress(normalizedCellRef) ];
                    }
                    if (coords.length > 0) {
                        const color = this.colors[this.colorIndex % this.colors.length];
                        this.colorIndex++, references.push({
                            address: uniqueKey,
                            coords: coords,
                            color: color,
                            isRange: isRange,
                            sheetName: sheetName
                        });
                    }
                } catch (e) {}
            }
        }
        return references;
    }
    parseRangeReference(rangeRef, activeSheet) {
        const parts = rangeRef.split(":");
        if (2 !== parts.length) throw new Error(`Invalid range reference: ${rangeRef}`);
        const startCoord = activeSheet.coordFromAddress(parts[0]), endCoord = activeSheet.coordFromAddress(parts[1]), coords = [], startRow = Math.min(startCoord.row, endCoord.row), endRow = Math.max(startCoord.row, endCoord.row), startCol = Math.min(startCoord.col, endCoord.col), endCol = Math.max(startCoord.col, endCoord.col);
        for (let row = startRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) coords.push({
            row: row,
            col: col
        });
        return coords;
    }
    highlightFormulaCells(formula) {
        this.clearHighlights();
        const references = this.parseCellReferences(formula);
        0 !== references.length && references.forEach((ref => {
            const targetSheet = ref.sheetName ? this.sheet.getSheetByName(ref.sheetName) : this.sheet.getActiveSheet();
            targetSheet && ref.coords.forEach((coord => {
                const key = `${ref.sheetName ? `${ref.sheetName}!` : ""}${coord.row}-${coord.col}`;
                this.highlightedCells.set(key, {
                    row: coord.row,
                    col: coord.col,
                    color: ref.color
                }), this.applyCellHighlight(targetSheet, coord, ref.color);
            }));
        }));
    }
    applyCellHighlight(sheet, coord, color) {
        const table = sheet.tableInstance;
        if (table && table.scenegraph) try {
            const key = `${coord.row}-${coord.col}`, highlightStyle = {
                borderColor: [ color, color, color, color ],
                borderLineWidth: [ 4, 4, 4, 4 ],
                borderLineDash: [ [ 4, 4 ], [ 4, 4 ], [ 4, 4 ], [ 4, 4 ] ],
                padding: [ 8, 8, 8, 8 ]
            }, styleId = `highlight-${key}`;
            table.registerCustomCellStyle(styleId, highlightStyle), table.arrangeCustomCellStyle({
                col: coord.col,
                row: coord.row
            }, styleId, !1);
        } catch (e) {}
    }
    clearHighlights() {
        const activeSheet = this.sheet.getActiveSheet();
        if (!activeSheet) return;
        const table = activeSheet.tableInstance;
        table && table.scenegraph && (this.highlightedCells.forEach((info => {
            try {
                table.arrangeCustomCellStyle({
                    col: info.col,
                    row: info.row
                }, null, !1);
            } catch (e) {}
        })), this.highlightedCells.clear(), this.colorIndex = 0);
    }
    getCellHighlightColor(coord) {
        const key = `${coord.row}-${coord.col}`, info = this.highlightedCells.get(key);
        return info ? info.color : null;
    }
    getHighlightedCells() {
        return Array.from(this.highlightedCells.values()).map((info => ({
            coord: {
                row: info.row,
                col: info.col
            },
            color: info.color
        })));
    }
    getColorizedFormula(formula) {
        const references = this.parseCellReferences(formula), parts = [];
        if (0 === references.length) return [ {
            text: formula
        } ];
        let lastIndex = 0;
        const colorMap = new Map;
        references.forEach((ref => {
            colorMap.set(ref.address.toUpperCase(), ref.color);
        }));
        const regex = /(\$?[A-Z]+\$?\d+)/gi;
        let match;
        for (;null !== (match = regex.exec(formula)); ) {
            match.index > lastIndex && parts.push({
                text: formula.substring(lastIndex, match.index)
            });
            const normalizedRef = match[0].replace(/\$/g, "").toUpperCase(), color = colorMap.get(normalizedRef);
            parts.push({
                text: match[0],
                color: color
            }), lastIndex = match.index + match[0].length;
        }
        return lastIndex < formula.length && parts.push({
            text: formula.substring(lastIndex)
        }), parts;
    }
    release() {
        this.clearHighlights(), this.highlightedCells.clear();
    }
}
//# sourceMappingURL=cell-highlight-manager.js.map