"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Worksheet = void 0;
const col_cache_1 = require("./utils/col-cache.js");
const range_1 = require("./range.js");
const row_1 = require("./row.js");
const column_1 = require("./column.js");
const enums_1 = require("./enums.js");
const image_1 = require("./image.js");
const table_1 = require("./table.js");
const data_validations_1 = require("./data-validations.js");
const form_control_1 = require("./form-control.js");
const encryptor_1 = require("./utils/encryptor.js");
const utils_1 = require("../../utils/utils.js");
const pivot_table_1 = require("./pivot-table.js");
const copy_style_1 = require("./utils/copy-style.js");
// Worksheet requirements
//  Operate as sheet inside workbook or standalone
//  Load and Save from file and stream
//  Access/Add/Delete individual cells
//  Manage column widths and row heights
class Worksheet {
    constructor(options) {
        options = options || {};
        this._workbook = options.workbook;
        // in a workbook, each sheet will have a number
        this.id = options.id ?? 0;
        this.orderNo = options.orderNo ?? 0;
        // and a name - use the setter to ensure validation and truncation
        this.name = options.name || `sheet${this.id}`;
        // add a state
        this.state = options.state ?? "visible";
        // rows allows access organised by row. Sparse array of arrays indexed by row-1, col
        // Note: _rows is zero based. Must subtract 1 to go from cell.row to index
        this._rows = [];
        // column definitions
        this._columns = null;
        // column keys (addRow convenience): key ==> this._collumns index
        this._keys = {};
        // keep record of all merges
        this._merges = {};
        // record of all row and column pageBreaks
        this.rowBreaks = [];
        this.colBreaks = [];
        // for tabColor, default row height, outline levels, etc
        this.properties = Object.assign({}, {
            defaultRowHeight: 15,
            outlineLevelCol: 0,
            outlineLevelRow: 0
        }, options.properties);
        // for all things printing
        this.pageSetup = Object.assign({}, {
            margins: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
            orientation: "portrait",
            // Excel does not normally write these unless explicitly set.
            // Historically we used 4294967295 as a sentinel when parsing, but emitting it
            // can cause strict Excel parsers to treat the workbook as corrupted.
            horizontalDpi: undefined,
            verticalDpi: undefined,
            fitToPage: !!(options.pageSetup &&
                (options.pageSetup.fitToWidth || options.pageSetup.fitToHeight) &&
                !options.pageSetup.scale),
            pageOrder: "downThenOver",
            blackAndWhite: false,
            draft: false,
            cellComments: "None",
            errors: "displayed",
            scale: 100,
            fitToWidth: 1,
            fitToHeight: 1,
            paperSize: undefined,
            showRowColHeaders: false,
            showGridLines: false,
            firstPageNumber: undefined,
            horizontalCentered: false,
            verticalCentered: false,
            rowBreaks: null,
            colBreaks: null
        }, options.pageSetup);
        this.headerFooter = Object.assign({}, {
            differentFirst: false,
            differentOddEven: false,
            oddHeader: null,
            oddFooter: null,
            evenHeader: null,
            evenFooter: null,
            firstHeader: null,
            firstFooter: null
        }, options.headerFooter);
        this.dataValidations = new data_validations_1.DataValidations();
        // for freezepanes, split, zoom, gridlines, etc
        this.views = options.views ?? [];
        this.autoFilter = options.autoFilter ?? null;
        // for images, etc
        this._media = [];
        // worksheet protection
        this.sheetProtection = null;
        // for tables
        this.tables = {};
        this.pivotTables = [];
        this.conditionalFormattings = [];
        // for form controls (legacy checkboxes, etc.)
        this.formControls = [];
    }
    get name() {
        return this._name;
    }
    set name(name) {
        if (name === undefined) {
            name = `sheet${this.id}`;
        }
        if (this._name === name) {
            return;
        }
        if (typeof name !== "string") {
            throw new Error("The name has to be a string.");
        }
        if (name === "") {
            throw new Error("The name can't be empty.");
        }
        if (name === "History") {
            throw new Error('The name "History" is protected. Please use a different name.');
        }
        // Illegal character in worksheet name: asterisk (*), question mark (?),
        // colon (:), forward slash (/ \), or bracket ([])
        if (/[*?:/\\[\]]/.test(name)) {
            throw new Error(`Worksheet name ${name} cannot include any of the following characters: * ? : \\ / [ ]`);
        }
        if (/(^')|('$)/.test(name)) {
            throw new Error(`The first or last character of worksheet name cannot be a single quotation mark: ${name}`);
        }
        if (name && name.length > 31) {
            if (process.env.NODE_ENV !== "production") {
                console.warn(`Worksheet name ${name} exceeds 31 chars. This will be truncated`);
            }
            name = name.substring(0, 31);
        }
        if (this._workbook.worksheets.find(ws => ws && ws.name.toLowerCase() === name.toLowerCase())) {
            throw new Error(`Worksheet name already exists: ${name}`);
        }
        this._name = name;
    }
    /**
     * The workbook that contains this worksheet
     */
    get workbook() {
        return this._workbook;
    }
    /**
     * When you're done with this worksheet, call this to remove from workbook
     */
    destroy() {
        this._workbook.removeWorksheetEx(this);
    }
    /**
     * Get the bounding range of the cells in this worksheet
     */
    get dimensions() {
        const dimensions = new range_1.Range();
        this._rows.forEach(row => {
            if (row) {
                const rowDims = row.dimensions;
                if (rowDims) {
                    dimensions.expand(row.number, rowDims.min, row.number, rowDims.max);
                }
            }
        });
        return dimensions;
    }
    // =========================================================================
    // Columns
    /**
     * Get the current columns array
     */
    get columns() {
        return this._columns;
    }
    /**
     * Add column headers and define column keys and widths.
     *
     * Note: these column structures are a workbook-building convenience only,
     * apart from the column width, they will not be fully persisted.
     */
    set columns(value) {
        // calculate max header row count
        this._headerRowCount = value.reduce((pv, cv) => {
            const headerCount = Array.isArray(cv.header) ? cv.header.length : cv.header ? 1 : 0;
            return Math.max(pv, headerCount);
        }, 0);
        // construct Column objects
        let count = 1;
        const columns = (this._columns = []);
        value.forEach(defn => {
            const column = new column_1.Column(this, count++, false);
            columns.push(column);
            column.defn = defn;
        });
    }
    getColumnKey(key) {
        return this._keys[key];
    }
    setColumnKey(key, value) {
        this._keys[key] = value;
    }
    deleteColumnKey(key) {
        delete this._keys[key];
    }
    eachColumnKey(f) {
        Object.keys(this._keys).forEach(key => f(this._keys[key], key));
    }
    /**
     * Access an individual column by key, letter and 1-based column number
     */
    getColumn(c) {
        let colNum;
        if (typeof c === "string") {
            // if it matches a key'd column, return that
            const col = this._keys[c];
            if (col) {
                return col;
            }
            // otherwise, assume letter
            colNum = col_cache_1.colCache.l2n(c);
        }
        else {
            colNum = c;
        }
        if (!this._columns) {
            this._columns = [];
        }
        if (colNum > this._columns.length) {
            let n = this._columns.length + 1;
            while (n <= colNum) {
                this._columns.push(new column_1.Column(this, n++));
            }
        }
        return this._columns[colNum - 1];
    }
    /**
     * Cut one or more columns (columns to the right are shifted left)
     * and optionally insert more
     *
     * If column properties have been defined, they will be cut or moved accordingly
     *
     * Known limitation: If a splice causes any merged cells to move, the results may be unpredictable
     *
     * Also: If the worksheet has more rows than values in the column inserts,
     * the rows will still be shifted as if the values existed
     */
    spliceColumns(start, count, ...inserts) {
        // Before splicing cells, release all cell-level merge references so that
        // row.splice copies plain values instead of merge proxies.
        // _spliceMerges (called later) will rebuild cell-level refs at new coordinates.
        for (const merge of Object.values(this._merges)) {
            for (let r = merge.top; r <= merge.bottom; r++) {
                for (let c = merge.left; c <= merge.right; c++) {
                    const cell = this.findCell(r, c);
                    if (cell && cell.type === enums_1.Enums.ValueType.Merge) {
                        cell.unmerge();
                    }
                }
            }
        }
        const rows = this._rows;
        const nRows = rows.length;
        if (inserts.length > 0) {
            // must iterate over all rows whether they exist yet or not
            for (let i = 0; i < nRows; i++) {
                const insertValues = inserts.map(insert => insert[i] ?? null);
                const row = this.getRow(i + 1);
                row.splice(start, count, ...insertValues);
            }
        }
        else {
            // nothing to insert, so just splice all rows
            this._rows.forEach(r => {
                if (r) {
                    r.splice(start, count);
                }
            });
        }
        // splice column definitions
        const nExpand = inserts.length - count;
        const nKeep = start + count;
        const nEnd = this._columns ? this._columns.length : 0;
        if (nExpand < 0) {
            for (let i = start + inserts.length; i <= nEnd; i++) {
                this.getColumn(i).defn = this.getColumn(i - nExpand).defn;
            }
        }
        else if (nExpand > 0) {
            for (let i = nEnd; i >= nKeep; i--) {
                this.getColumn(i + nExpand).defn = this.getColumn(i).defn;
            }
        }
        for (let i = start; i < start + inserts.length; i++) {
            this.getColumn(i).defn = undefined;
        }
        // account for defined names
        this.workbook.definedNames.spliceColumns(this.name, start, count, inserts.length);
        // account for images
        if (nExpand !== 0) {
            for (const image of this._media) {
                if (image.type === "image" && image.range) {
                    const { tl, br } = image.range;
                    if (tl && tl.nativeCol >= start - 1) {
                        tl.nativeCol = Math.max(0, tl.nativeCol + nExpand);
                    }
                    if (br && br.nativeCol >= start - 1) {
                        br.nativeCol = Math.max(0, br.nativeCol + nExpand);
                    }
                }
            }
        }
        // account for merges
        this._spliceMerges("col", start, count, inserts.length);
    }
    /**
     * Get the last column in a worksheet
     */
    get lastColumn() {
        return this.getColumn(this.columnCount);
    }
    /**
     * The total column size of the document. Equal to the maximum cell count from all of the rows
     */
    get columnCount() {
        let maxCount = 0;
        this.eachRow(row => {
            maxCount = Math.max(maxCount, row.cellCount);
        });
        return maxCount;
    }
    /**
     * A count of the number of columns that have values
     */
    get actualColumnCount() {
        // performance nightmare - for each row, counts all the columns used
        const counts = [];
        let count = 0;
        this.eachRow(row => {
            row.eachCell(({ col }) => {
                if (!counts[col]) {
                    counts[col] = true;
                    count++;
                }
            });
        });
        return count;
    }
    // =========================================================================
    // Rows
    _commitRow(row) {
        // nop - allows streaming reader to fill a document
    }
    get _lastRowNumber() {
        // need to cope with results of splice
        const rows = this._rows;
        let n = rows.length;
        while (n > 0 && rows[n - 1] === undefined) {
            n--;
        }
        return n;
    }
    get _nextRow() {
        return this._lastRowNumber + 1;
    }
    /**
     * Get the last editable row in a worksheet (or undefined if there are none)
     */
    get lastRow() {
        if (this._rows.length) {
            return this._rows[this._rows.length - 1];
        }
        return undefined;
    }
    /**
     * Tries to find and return row for row number, else undefined
     *
     * @param r - The 1-indexed row number
     */
    findRow(r) {
        return this._rows[r - 1];
    }
    /**
     * Tries to find and return rows for row number start and length, else undefined
     *
     * @param start - The 1-indexed starting row number
     * @param length - The length of the expected array
     */
    findRows(start, length) {
        return this._rows.slice(start - 1, start - 1 + length);
    }
    /**
     * The total row size of the document. Equal to the row number of the last row that has values.
     */
    get rowCount() {
        return this._lastRowNumber;
    }
    /**
     * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count.
     */
    get actualRowCount() {
        // counts actual rows that have actual data
        let count = 0;
        this.eachRow(() => {
            count++;
        });
        return count;
    }
    // get a row by row number.
    getRow(r) {
        let row = this._rows[r - 1];
        if (!row) {
            row = this._rows[r - 1] = new row_1.Row(this, r);
        }
        return row;
    }
    // get multiple rows by row number.
    getRows(start, length) {
        if (length < 1) {
            return undefined;
        }
        const rows = [];
        for (let i = start; i < start + length; i++) {
            rows.push(this.getRow(i));
        }
        return rows;
    }
    addRow(value, style = "n") {
        const rowNo = this._nextRow;
        const row = this.getRow(rowNo);
        row.values = value;
        this._setStyleOption(rowNo, style[0] === "i" ? style : "n");
        return row;
    }
    addRows(value, style = "n") {
        const rows = [];
        value.forEach(row => {
            rows.push(this.addRow(row, style));
        });
        return rows;
    }
    insertRow(pos, value, style = "n") {
        this.spliceRows(pos, 0, value);
        this._setStyleOption(pos, style);
        return this.getRow(pos);
    }
    insertRows(pos, values, style = "n") {
        this.spliceRows(pos, 0, ...values);
        if (style !== "n") {
            // copy over the styles
            for (let i = 0; i < values.length; i++) {
                if (style[0] === "o" && this.findRow(values.length + pos + i) !== undefined) {
                    this._copyStyle(values.length + pos + i, pos + i, style[1] === "+");
                }
                else if (style[0] === "i" && this.findRow(pos - 1) !== undefined) {
                    this._copyStyle(pos - 1, pos + i, style[1] === "+");
                }
            }
        }
        return this.getRows(pos, values.length);
    }
    // set row at position to same style as of either pervious row (option 'i') or next row (option 'o')
    _setStyleOption(pos, style = "n") {
        if (style[0] === "o" && this.findRow(pos + 1) !== undefined) {
            this._copyStyle(pos + 1, pos, style[1] === "+");
        }
        else if (style[0] === "i" && this.findRow(pos - 1) !== undefined) {
            this._copyStyle(pos - 1, pos, style[1] === "+");
        }
    }
    _copyStyle(src, dest, styleEmpty = false) {
        const rSrc = this.getRow(src);
        const rDst = this.getRow(dest);
        rDst.style = (0, copy_style_1.copyStyle)(rSrc.style);
        rSrc.eachCell({ includeEmpty: styleEmpty }, (cell, colNumber) => {
            rDst.getCell(colNumber).style = (0, copy_style_1.copyStyle)(cell.style);
        });
        rDst.height = rSrc.height;
    }
    /**
     * Duplicate rows and insert new rows
     */
    duplicateRow(rowNum, count, insert = false) {
        // create count duplicates of rowNum
        // either inserting new or overwriting existing rows
        const rSrc = this._rows[rowNum - 1];
        const inserts = Array.from({ length: count }).fill(rSrc.values);
        // Collect single-row merges from the source row before splicing
        // (only merges where top == bottom == rowNum, i.e. horizontal merges within one row)
        const srcMerges = [];
        for (const merge of Object.values(this._merges)) {
            if (merge.top === rowNum && merge.bottom === rowNum) {
                srcMerges.push(merge);
            }
        }
        // Collect images anchored to the source row before splicing
        // (images whose top-left anchor is on the source row)
        const srcImages = [];
        const srcRow0 = rowNum - 1; // 0-based source row
        for (const image of this._media) {
            if (image.type === "image" && image.range) {
                if (image.range.tl.nativeRow === srcRow0) {
                    srcImages.push(image);
                }
            }
        }
        this.spliceRows(rowNum + 1, insert ? 0 : count, ...inserts);
        // now copy styles...
        for (let i = 0; i < count; i++) {
            const rDst = this._rows[rowNum + i];
            rDst.style = rSrc.style;
            rDst.height = rSrc.height;
            rSrc.eachCell({ includeEmpty: true }, (cell, colNumber) => {
                rDst.getCell(colNumber).style = cell.style;
            });
        }
        // Duplicate single-row merges from source row into each new row
        if (srcMerges.length > 0) {
            for (let i = 0; i < count; i++) {
                const dstRow = rowNum + 1 + i;
                // In overwrite mode, clear any existing merges in the target row
                if (!insert) {
                    const toRemove = [];
                    for (const [key, merge] of Object.entries(this._merges)) {
                        if (merge.top <= dstRow && merge.bottom >= dstRow) {
                            toRemove.push(key);
                        }
                    }
                    for (const key of toRemove) {
                        this._unMergeMaster(this.getCell(key));
                    }
                }
                for (const srcMerge of srcMerges) {
                    this.mergeCellsWithoutStyle(dstRow, srcMerge.left, dstRow, srcMerge.right);
                }
            }
        }
        // Duplicate images from source row into each new row.
        // In overwrite mode, first remove any images anchored to the target rows
        // so they don't coexist with the clones (mirrors merge cleanup above).
        if (!insert) {
            const dstStart0 = rowNum; // first target row, 0-based (1-based rowNum + 1 → 0-based rowNum)
            const dstEnd0 = rowNum + count - 1; // last target row, 0-based
            this._media = this._media.filter(image => {
                if (image.type === "image" && image.range) {
                    const row0 = image.range.tl.nativeRow;
                    return row0 < dstStart0 || row0 > dstEnd0;
                }
                return true;
            });
        }
        for (let i = 0; i < count; i++) {
            const rowDelta = i + 1; // offset from source row to target row
            for (const srcImage of srcImages) {
                const cloned = srcImage.clone();
                cloned.range.tl.nativeRow = srcRow0 + rowDelta;
                if (cloned.range.br) {
                    const brDelta = srcImage.range.br.nativeRow - srcRow0;
                    cloned.range.br.nativeRow = srcRow0 + rowDelta + brDelta;
                }
                this._media.push(cloned);
            }
        }
    }
    /**
     * Cut one or more rows (rows below are shifted up)
     * and optionally insert more
     *
     * Known limitation: If a splice causes any merged cells to move, the results may be unpredictable
     */
    spliceRows(start, count, ...inserts) {
        // same problem as row.splice, except worse.
        // Before splicing rows, release all cell-level merge references so that
        // row value copies work on plain values instead of merge proxies.
        // _spliceMerges (called later) will rebuild cell-level refs at new coordinates.
        for (const merge of Object.values(this._merges)) {
            for (let r = merge.top; r <= merge.bottom; r++) {
                for (let c = merge.left; c <= merge.right; c++) {
                    const cell = this.findCell(r, c);
                    if (cell && cell.type === enums_1.Enums.ValueType.Merge) {
                        cell.unmerge();
                    }
                }
            }
        }
        const nKeep = start + count;
        const nInserts = inserts.length;
        const nExpand = nInserts - count;
        const nEnd = this._rows.length;
        let i;
        let rSrc;
        if (nExpand < 0) {
            // remove rows
            if (start === nEnd) {
                this._rows[nEnd - 1] = undefined;
            }
            for (i = nKeep; i <= nEnd; i++) {
                rSrc = this._rows[i - 1];
                if (rSrc) {
                    const rDst = this.getRow(i + nExpand);
                    rDst.values = rSrc.values;
                    rDst.style = rSrc.style;
                    rDst.height = rSrc.height;
                    rSrc.eachCell({ includeEmpty: true }, (cell, colNumber) => {
                        rDst.getCell(colNumber).style = cell.style;
                    });
                    this._rows[i - 1] = undefined;
                }
                else {
                    this._rows[i + nExpand - 1] = undefined;
                }
            }
        }
        else if (nExpand > 0) {
            // insert new cells
            for (i = nEnd; i >= nKeep; i--) {
                rSrc = this._rows[i - 1];
                if (rSrc) {
                    const rDst = this.getRow(i + nExpand);
                    rDst.values = rSrc.values;
                    rDst.style = rSrc.style;
                    rDst.height = rSrc.height;
                    rSrc.eachCell({ includeEmpty: true }, (cell, colNumber) => {
                        rDst.getCell(colNumber).style = cell.style;
                    });
                }
                else {
                    this._rows[i + nExpand - 1] = undefined;
                }
            }
        }
        // now copy over the new values
        for (i = 0; i < nInserts; i++) {
            const rDst = this.getRow(start + i);
            rDst.style = {};
            rDst.values = inserts[i];
        }
        // account for defined names
        this.workbook.definedNames.spliceRows(this.name, start, count, nInserts);
        // account for images
        if (nExpand !== 0) {
            for (const image of this._media) {
                if (image.type === "image" && image.range) {
                    const { tl, br } = image.range;
                    if (tl && tl.nativeRow >= start - 1) {
                        tl.nativeRow = Math.max(0, tl.nativeRow + nExpand);
                    }
                    if (br && br.nativeRow >= start - 1) {
                        br.nativeRow = Math.max(0, br.nativeRow + nExpand);
                    }
                }
            }
        }
        // account for merges
        this._spliceMerges("row", start, count, nInserts);
    }
    eachRow(optOrCallback, maybeCallback) {
        let options;
        let callback;
        if (typeof optOrCallback === "function") {
            callback = optOrCallback;
        }
        else {
            options = optOrCallback;
            callback = maybeCallback;
        }
        if (options && options.includeEmpty) {
            const n = this._rows.length;
            for (let i = 1; i <= n; i++) {
                callback(this.getRow(i), i);
            }
        }
        else {
            this._rows.forEach(row => {
                if (row && row.hasValues) {
                    callback(row, row.number);
                }
            });
        }
    }
    /**
     * Return all rows as sparse array
     */
    getSheetValues() {
        const rows = [];
        this._rows.forEach(row => {
            if (row) {
                rows[row.number] = row.values;
            }
        });
        return rows;
    }
    // =========================================================================
    // Cells
    /**
     * Returns the cell at [r,c] or address given by r. If not found, return undefined
     */
    findCell(r, c) {
        const address = col_cache_1.colCache.getAddress(r, c);
        const row = this._rows[address.row - 1];
        return row ? row.findCell(address.col) : undefined;
    }
    /**
     * Get or create cell at [r,c] or address given by r
     */
    getCell(r, c) {
        const address = col_cache_1.colCache.getAddress(r, c);
        const row = this.getRow(address.row);
        return row.getCellEx(address);
    }
    // =========================================================================
    // Merge
    /**
     * Merge cells, either:
     *
     * tlbr string, e.g. `'A4:B5'`
     *
     * tl string, br string, e.g. `'G10', 'H11'`
     *
     * t, l, b, r numbers, e.g. `10,11,12,13`
     */
    mergeCells(...cells) {
        const dimensions = new range_1.Range(cells);
        this._mergeCellsInternal(dimensions);
    }
    mergeCellsWithoutStyle(...cells) {
        const dimensions = new range_1.Range(cells);
        this._mergeCellsInternal(dimensions, true);
    }
    _mergeCellsInternal(dimensions, ignoreStyle) {
        // check cells aren't already merged
        Object.values(this._merges).forEach((merge) => {
            if (merge.intersects(dimensions)) {
                throw new Error("Cannot merge already merged cells");
            }
        });
        // apply merge
        const master = this.getCell(dimensions.top, dimensions.left);
        for (let i = dimensions.top; i <= dimensions.bottom; i++) {
            for (let j = dimensions.left; j <= dimensions.right; j++) {
                // merge all but the master cell
                if (i > dimensions.top || j > dimensions.left) {
                    this.getCell(i, j).merge(master, ignoreStyle);
                }
            }
        }
        // index merge
        this._merges[master.address] = dimensions;
    }
    _unMergeMaster(master) {
        // master is always top left of a rectangle
        const merge = this._merges[master.address];
        if (merge) {
            for (let i = merge.top; i <= merge.bottom; i++) {
                for (let j = merge.left; j <= merge.right; j++) {
                    this.getCell(i, j).unmerge();
                }
            }
            delete this._merges[master.address];
        }
    }
    /**
     * Update _merges dictionary and cell-level merge references after a row or column splice.
     */
    _spliceMerges(axis, start, count, nInserts) {
        const nExpand = nInserts - count;
        if (nExpand === 0 && count === 0) {
            return;
        }
        const nKeep = start + count;
        const isRow = axis === "row";
        const newMerges = {};
        for (const merge of Object.values(this._merges)) {
            const { top, left, bottom, right } = merge.model;
            // For row axis: lo=top, hi=bottom. For col axis: lo=left, hi=right.
            const lo = isRow ? top : left;
            const hi = isRow ? bottom : right;
            if (nExpand <= 0 && count > 0) {
                // Deleting rows/columns
                const deleteEnd = nKeep - 1;
                if (lo > deleteEnd) {
                    // Entirely after deleted range — shift
                    const newRange = isRow
                        ? new range_1.Range(top + nExpand, left, bottom + nExpand, right)
                        : new range_1.Range(top, left + nExpand, bottom, right + nExpand);
                    newMerges[col_cache_1.colCache.encodeAddress(newRange.top, newRange.left)] = newRange;
                }
                else if (hi < start) {
                    // Entirely before deleted range — unchanged
                    newMerges[col_cache_1.colCache.encodeAddress(top, left)] = merge;
                }
                else if (lo >= start && hi <= deleteEnd) {
                    // Entirely within deleted range — remove
                }
                else {
                    // Spans splice boundary — shrink
                    let newTop = top;
                    let newLeft = left;
                    let newBottom = bottom;
                    let newRight = right;
                    if (isRow) {
                        newTop = top < start ? top : start;
                        newBottom = Math.max(newTop, bottom + nExpand);
                    }
                    else {
                        newLeft = left < start ? left : start;
                        newRight = Math.max(newLeft, right + nExpand);
                    }
                    const newRange = new range_1.Range(newTop, newLeft, newBottom, newRight);
                    if (newTop === newBottom && newLeft === newRight) {
                        // Degenerate 1x1 merge — remove instead of keeping
                    }
                    else {
                        newMerges[col_cache_1.colCache.encodeAddress(newRange.top, newRange.left)] = newRange;
                    }
                }
            }
            else {
                // Inserting rows/columns: shift items at/after nKeep
                if (lo >= nKeep) {
                    // Entirely at or after splice — shift
                    const newRange = isRow
                        ? new range_1.Range(top + nExpand, left, bottom + nExpand, right)
                        : new range_1.Range(top, left + nExpand, bottom, right + nExpand);
                    newMerges[col_cache_1.colCache.encodeAddress(newRange.top, newRange.left)] = newRange;
                }
                else if (hi < nKeep) {
                    // Entirely before splice — unchanged
                    newMerges[col_cache_1.colCache.encodeAddress(top, left)] = merge;
                }
                else {
                    // Spans splice boundary — stretch
                    if (isRow) {
                        merge.model.bottom = bottom + nExpand;
                    }
                    else {
                        merge.model.right = right + nExpand;
                    }
                    newMerges[col_cache_1.colCache.encodeAddress(top, left)] = merge;
                }
            }
        }
        this._merges = newMerges;
        // Rebuild cell-level merge references for all merges.
        // Pre-unmerge in spliceRows/spliceColumns clears all cell refs,
        // so we must rebuild every merge, not just moved/resized ones.
        for (const m of Object.values(newMerges)) {
            const master = this.getCell(m.top, m.left);
            for (let r = m.top; r <= m.bottom; r++) {
                for (let c = m.left; c <= m.right; c++) {
                    if (r > m.top || c > m.left) {
                        this.getCell(r, c).merge(master, true);
                    }
                }
            }
        }
    }
    get hasMerges() {
        // return true if this._merges has a merge object
        return Object.values(this._merges).some(Boolean);
    }
    /**
     * Scan the range and if any cell is part of a merge, un-merge the group.
     * Note this function can affect multiple merges and merge-blocks are
     * atomic - either they're all merged or all un-merged.
     */
    unMergeCells(...cells) {
        const dimensions = new range_1.Range(cells);
        // find any cells in that range and unmerge them
        for (let i = dimensions.top; i <= dimensions.bottom; i++) {
            for (let j = dimensions.left; j <= dimensions.right; j++) {
                const cell = this.findCell(i, j);
                if (cell) {
                    if (cell.type === enums_1.Enums.ValueType.Merge) {
                        // this cell merges to another master
                        this._unMergeMaster(cell.master);
                    }
                    else if (this._merges[cell.address]) {
                        // this cell is a master
                        this._unMergeMaster(cell);
                    }
                }
            }
        }
    }
    // ===========================================================================
    // Shared/Array Formula
    fillFormula(range, formula, results, shareType = "shared") {
        // Define formula for top-left cell and share to rest
        const decoded = col_cache_1.colCache.decode(range);
        const { top, left, bottom, right } = decoded;
        const width = right - left + 1;
        const masterAddress = col_cache_1.colCache.encodeAddress(top, left);
        const isShared = shareType === "shared";
        // work out result accessor
        let getResult;
        if (typeof results === "function") {
            getResult = results;
        }
        else if (Array.isArray(results)) {
            if (Array.isArray(results[0])) {
                getResult = (row, col) => results[row - top][col - left];
            }
            else {
                getResult = (row, col) => results[(row - top) * width + (col - left)];
            }
        }
        else {
            getResult = () => undefined;
        }
        let first = true;
        for (let r = top; r <= bottom; r++) {
            for (let c = left; c <= right; c++) {
                if (first) {
                    const cell = this.getCell(r, c);
                    const formulaValue = {
                        shareType,
                        formula,
                        ref: range,
                        result: getResult(r, c)
                    };
                    cell.value = formulaValue;
                    first = false;
                }
                else {
                    this.getCell(r, c).value = isShared
                        ? {
                            sharedFormula: masterAddress,
                            result: getResult(r, c)
                        }
                        : getResult(r, c);
                }
            }
        }
    }
    // =========================================================================
    // Images
    /**
     * Using the image id from `Workbook.addImage`,
     * embed an image within the worksheet to cover a range
     */
    addImage(imageId, range) {
        const model = {
            type: "image",
            imageId: String(imageId),
            range
        };
        this._media.push(new image_1.Image(this, model));
    }
    getImages() {
        return this._media.filter(m => m.type === "image");
    }
    /**
     * Using the image id from `Workbook.addImage`, set the background to the worksheet
     */
    addBackgroundImage(imageId) {
        const model = {
            type: "background",
            imageId: String(imageId)
        };
        this._media.push(new image_1.Image(this, model));
    }
    getBackgroundImageId() {
        const image = this._media.find(m => m.type === "background");
        return image && image.imageId;
    }
    // =========================================================================
    // Form Controls (Legacy Checkboxes)
    /**
     * Add a form control checkbox to the worksheet.
     *
     * Form control checkboxes are the legacy style that work in Office 2007+,
     * WPS Office, LibreOffice, and other spreadsheet applications.
     *
     * Unlike modern in-cell checkboxes (which only work in Microsoft 365),
     * form control checkboxes are floating controls positioned over cells.
     *
     * @param range - Cell reference (e.g., "B2") or range (e.g., "B2:D3") for positioning
     * @param options - Checkbox options
     * @returns The created FormCheckbox instance
     *
     * @example
     * // Simple checkbox at B2
     * ws.addFormCheckbox("B2");
     *
     * // Checkbox with label and linked cell
     * ws.addFormCheckbox("B2:D3", {
     *   text: "Accept terms",
     *   link: "A2",
     *   checked: false
     * });
     */
    addFormCheckbox(range, options) {
        const checkbox = new form_control_1.FormCheckbox(this, range, options);
        this.formControls.push(checkbox);
        return checkbox;
    }
    /**
     * Get all form control checkboxes in the worksheet
     */
    getFormCheckboxes() {
        return this.formControls;
    }
    // =========================================================================
    // Worksheet Protection
    /**
     * Protect the worksheet with optional password and options
     */
    async protect(password, options) {
        this.sheetProtection = {
            sheet: true
        };
        if (options && "spinCount" in options) {
            // force spinCount to be integer >= 0
            options.spinCount = Number.isFinite(options.spinCount)
                ? Math.round(Math.max(0, options.spinCount))
                : 100000;
        }
        if (password) {
            this.sheetProtection.algorithmName = "SHA-512";
            this.sheetProtection.saltValue = (0, utils_1.uint8ArrayToBase64)(encryptor_1.Encryptor.randomBytes(16));
            this.sheetProtection.spinCount =
                options && "spinCount" in options ? options.spinCount : 100000; // allow user specified spinCount
            this.sheetProtection.hashValue = await encryptor_1.Encryptor.convertPasswordToHash(password, "SHA-512", this.sheetProtection.saltValue, this.sheetProtection.spinCount);
        }
        if (options) {
            this.sheetProtection = Object.assign(this.sheetProtection, options);
            if (!password && "spinCount" in options) {
                delete this.sheetProtection.spinCount;
            }
        }
    }
    unprotect() {
        this.sheetProtection = null;
    }
    // =========================================================================
    // Tables
    /**
     * Add a new table and return a reference to it
     */
    addTable(model) {
        const table = new table_1.Table(this, model);
        this.tables[model.name] = table;
        return table;
    }
    /**
     * Fetch table by name
     */
    getTable(name) {
        return this.tables[name];
    }
    /**
     * Delete table by name
     */
    removeTable(name) {
        delete this.tables[name];
    }
    /**
     * Fetch all tables in the worksheet
     */
    getTables() {
        return Object.values(this.tables);
    }
    // =========================================================================
    // Pivot Tables
    addPivotTable(model) {
        const pivotTable = (0, pivot_table_1.makePivotTable)(this, model);
        this.pivotTables.push(pivotTable);
        this.workbook.pivotTables.push(pivotTable);
        return pivotTable;
    }
    // ===========================================================================
    // Conditional Formatting
    /**
     * Add conditional formatting rules
     */
    addConditionalFormatting(cf) {
        this.conditionalFormattings.push(cf);
    }
    /**
     * Delete conditional formatting rules
     */
    removeConditionalFormatting(filter) {
        if (typeof filter === "number") {
            this.conditionalFormattings.splice(filter, 1);
        }
        else if (filter instanceof Function) {
            this.conditionalFormattings = this.conditionalFormattings.filter(filter);
        }
        else {
            this.conditionalFormattings = [];
        }
    }
    // ===========================================================================
    // Model
    get model() {
        const model = {
            id: this.id,
            name: this.name,
            dataValidations: this.dataValidations.model,
            properties: this.properties,
            state: this.state,
            pageSetup: this.pageSetup,
            headerFooter: this.headerFooter,
            rowBreaks: this.rowBreaks,
            colBreaks: this.colBreaks,
            views: this.views,
            autoFilter: this.autoFilter,
            media: this._media.map(medium => medium.model),
            sheetProtection: this.sheetProtection,
            tables: Object.values(this.tables).map(table => table.model),
            pivotTables: this.pivotTables,
            conditionalFormattings: this.conditionalFormattings,
            formControls: this.formControls.map(fc => fc.model),
            drawing: this._drawing
        };
        // =================================================
        // columns
        model.cols = column_1.Column.toModel(this.columns ?? []);
        // ==========================================================
        // Rows
        const rows = (model.rows = []);
        const dimensions = (model.dimensions = new range_1.Range());
        this._rows.forEach(row => {
            const rowModel = row && row.model;
            if (rowModel) {
                dimensions.expand(rowModel.number, rowModel.min, rowModel.number, rowModel.max);
                rows.push(rowModel);
            }
        });
        // ==========================================================
        // Merges
        model.merges = [];
        Object.values(this._merges).forEach((merge) => {
            model.merges.push(merge.range);
        });
        return model;
    }
    _parseRows(model) {
        this._rows = [];
        if (model.rows) {
            model.rows.forEach(rowModel => {
                const row = new row_1.Row(this, rowModel.number);
                this._rows[row.number - 1] = row;
                row.model = rowModel;
            });
        }
    }
    _parseMergeCells(model) {
        if (model.mergeCells) {
            model.mergeCells.forEach((merge) => {
                // Do not merge styles when importing an Excel file
                // since each cell may have different styles intentionally.
                this.mergeCellsWithoutStyle(merge);
            });
        }
    }
    set model(value) {
        this.name = value.name;
        this._columns = column_1.Column.fromModel(this, value.cols);
        this._parseRows(value);
        this._parseMergeCells(value);
        this.dataValidations = new data_validations_1.DataValidations(value.dataValidations);
        this.properties = value.properties;
        this.pageSetup = value.pageSetup;
        this.headerFooter = value.headerFooter;
        this.rowBreaks = value.rowBreaks ?? [];
        this.colBreaks = value.colBreaks ?? [];
        this.views = value.views;
        this.autoFilter = value.autoFilter;
        this._media = value.media.map(medium => new image_1.Image(this, medium));
        this.sheetProtection = value.sheetProtection;
        this.tables = value.tables.reduce((tables, table) => {
            const t = new table_1.Table(this, table);
            t.model = table;
            tables[table.name] = t;
            return tables;
        }, {});
        this.pivotTables = value.pivotTables;
        this.conditionalFormattings = value.conditionalFormattings;
        // Form controls are currently write-only (not parsed from XLSX)
        this.formControls = [];
        // Preserve loaded drawing data (charts, etc.)
        this._drawing = value.drawing;
    }
}
exports.Worksheet = Worksheet;
