"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "collapseNode", {
    enumerable: true,
    get: function() {
        return collapseNode;
    }
});
const _array = require("../../../../helpers/array");
const _expand = require("./expand");
const _tree = require("./utils/tree");
function collapseNode(nodeToProcess) {
    const { data: nodeData, childs: nodeChilds } = nodeToProcess;
    if (nodeData.isCollapsed || nodeData.isHidden || nodeData.origColspan <= 1) {
        return {
            rollbackModification: ()=>{},
            affectedColumns: [],
            colspanCompensation: 0
        };
    }
    const isNodeReflected = (0, _tree.isNodeReflectsFirstChildColspan)(nodeToProcess);
    if (isNodeReflected) {
        return collapseNode(nodeChilds[0]);
    }
    nodeData.isCollapsed = true;
    const allLeavesExceptMostLeft = nodeChilds.slice(1);
    const affectedColumns = new Set();
    if (allLeavesExceptMostLeft.length > 0) {
        (0, _array.arrayEach)(allLeavesExceptMostLeft, (node)=>{
            (0, _tree.traverseHiddenNodeColumnIndexes)(node, (gridColumnIndex)=>{
                affectedColumns.add(gridColumnIndex);
            });
            // Clone the tree to preserve original tree state after header expanding.
            node.data.clonedTree = node.cloneTree();
            // Hide all leaves except the first leaf on the left (on headers context hide all
            // headers on the right).
            node.walkDown(({ data })=>{
                data.isHidden = true;
            });
        });
    } else {
        const { origColspan, columnIndex } = nodeData;
        // Add column to "affected" started from 1. The header without children can not be
        // collapsed so the first have to be visible (untouched).
        for(let i = 1; i < origColspan; i++){
            const gridColumnIndex = columnIndex + i;
            affectedColumns.add(gridColumnIndex);
        }
    }
    // Calculate by how many colspan it needs to reduce the headings to match them to
    // the first child colspan width.
    const colspanCompensation = nodeData.colspan - ((0, _tree.getFirstChildProperty)(nodeToProcess, 'colspan') ?? 1);
    nodeToProcess.walkUp((node)=>{
        const { data } = node;
        data.colspan -= colspanCompensation;
        if (data.colspan <= 1) {
            data.colspan = 1;
            data.isCollapsed = true;
        } else if ((0, _tree.isNodeReflectsFirstChildColspan)(node)) {
            data.isCollapsed = (0, _tree.getFirstChildProperty)(node, 'isCollapsed');
        }
    });
    return {
        rollbackModification: ()=>(0, _expand.expandNode)(nodeToProcess),
        affectedColumns: Array.from(affectedColumns),
        colspanCompensation
    };
}
