"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertEmptyColumn = void 0;
const state_1 = require("../../../../../../pm/state.js");
const lodash_1 = require("../../../../../../lodash.js");
const table_desc_1 = require("../../../../../../table-utils/table-desc.js");
const YfmTableSpecs_1 = require("../../../YfmTableSpecs/index.js");
const insertEmptyColumn = (params) => {
    return (state, dispatch) => {
        const table = state.doc.nodeAt(params.tablePos);
        const tableDesc = table && table_desc_1.TableDesc.create(table)?.bind(params.tablePos);
        if (!tableDesc)
            return false;
        const colIdx = Math.min(Math.max(params.colIndex, 0), tableDesc.cols);
        if (dispatch) {
            const posToInsert = [];
            const incrementColspan = [];
            if (colIdx === 0) {
                posToInsert.push(...tableDesc.getPosForColumn(0).map((pos) => getCellPos(pos, 'start')));
            }
            else if (colIdx === tableDesc.cols) {
                posToInsert.push(...tableDesc
                    .getPosForColumn(tableDesc.cols - 1)
                    .map((pos) => getCellPos(pos, 'end')));
            }
            else {
                for (let rowIdx = 0; rowIdx < tableDesc.rows; rowIdx++) {
                    const cell = tableDesc.base.rowsDesc[rowIdx].cells[colIdx];
                    if (cell.type === 'virtual' && cell.colspan && cell.colspan[1] !== colIdx) {
                        incrementColspan.push(cell.colspan);
                    }
                    else {
                        posToInsert.push(getCellPos(tableDesc.getPosForCell(rowIdx, colIdx), 'start'));
                    }
                }
            }
            const { tr } = state;
            const td = (0, YfmTableSpecs_1.yfmTableCellType)(state.schema);
            for (const [rowIdx, colIdx] of (0, lodash_1.uniqWith)(incrementColspan, lodash_1.isEqual)) {
                const cell = tableDesc.base.rowsDesc[rowIdx].cells[colIdx];
                const cellPos = tableDesc.getPosForCell(rowIdx, colIdx);
                tr.setNodeAttribute(cellPos.from, 'colspan', cell.colspan + 1);
            }
            for (const pos of posToInsert) {
                tr.insert(tr.mapping.map(pos), td.createAndFill());
            }
            tr.setSelection(state_1.TextSelection.near(tr.doc.resolve(posToInsert[0]), 1));
            dispatch(tr.scrollIntoView());
        }
        return true;
    };
};
exports.insertEmptyColumn = insertEmptyColumn;
function getCellPos(pos, dir) {
    if (pos.type === 'virtual')
        return pos.closestPos;
    return dir === 'start' ? pos.from : pos.to;
}
//# sourceMappingURL=insert-empty-column.js.map
