"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "expandNode", {
    enumerable: true,
    get: function() {
        return expandNode;
    }
});
const _array = require("../../../../helpers/array");
const _collapse = require("./collapse");
const _tree = require("./utils/tree");
function expandNode(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 expandNode(nodeChilds[0]);
    }
    nodeData.isCollapsed = false;
    const allLeavesExceptMostLeft = nodeChilds.slice(1);
    const affectedColumns = new Set();
    let colspanCompensation = 0;
    if (allLeavesExceptMostLeft.length > 0) {
        (0, _array.arrayEach)(allLeavesExceptMostLeft, (node)=>{
            // Restore original state of the collapsed headers.
            node.replaceTreeWith(node.data.clonedTree);
            node.data.clonedTree = null;
            const leafData = node.data;
            // Calculate by how many colspan it needs to increase the headings to match them to
            // the colspan width of all its children.
            colspanCompensation += leafData.colspan;
            (0, _tree.traverseHiddenNodeColumnIndexes)(node, (gridColumnIndex)=>{
                affectedColumns.add(gridColumnIndex);
            });
        });
    } else {
        const { colspan, origColspan, columnIndex } = nodeData;
        // In a case when the node doesn't have any children restore the colspan width to
        // its original state.
        colspanCompensation = origColspan - colspan;
        // Add column to "affected" started from 1. The header without children can not be
        // collapsed so the first column is already visible and we shouldn't touch it.
        for(let i = 1; i < origColspan; i++){
            affectedColumns.add(columnIndex + i);
        }
    }
    nodeToProcess.walkUp((node)=>{
        const { data } = node;
        data.colspan += colspanCompensation;
        if (data.colspan >= data.origColspan) {
            data.colspan = data.origColspan;
            data.isCollapsed = false;
        } else if ((0, _tree.isNodeReflectsFirstChildColspan)(node)) {
            data.isCollapsed = (0, _tree.getFirstChildProperty)(node, 'isCollapsed');
        }
    });
    return {
        rollbackModification: ()=>(0, _collapse.collapseNode)(nodeToProcess),
        affectedColumns: Array.from(affectedColumns),
        colspanCompensation
    };
}
