"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "traverseTree", {
    enumerable: true,
    get: function() {
        return traverseTree;
    }
});
const _dedupe = /*#__PURE__*/ _interop_require_default(require("classnames/dedupe"));
const _utils = require(".");
const _Treetokens = require("../Tree.tokens");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
// Поиск в глубину для обхода узлов дерева.
const dfs = (node, selectedKeys, rootParentsSelected, parents)=>{
    if (selectedKeys.has(node.key)) {
        parents.forEach((parent)=>{
            parent.className = (0, _dedupe.default)(parent.className, _Treetokens.classes.treeItemHasSelectedChildren);
        });
    }
    node.children?.forEach((childNode)=>dfs(childNode, selectedKeys, rootParentsSelected, [
            ...parents,
            node
        ]));
    if (rootParentsSelected.has(parents.filter((parent)=>parent.key !== 'root')[0]?.key)) {
        node.className = (0, _dedupe.default)(node.className, _Treetokens.classes.treeItemPrimaryBackground);
    }
    if (!node.children) {
        node.className = (0, _dedupe.default)(node.className, _Treetokens.classes.treeLeafNode);
    }
};
const getRootParentsSelectedChildren = (node, selectedKeysSet)=>{
    const rootParentsSelected = new Set();
    const dfs = (node, currentRootParentKey)=>{
        if (rootParentsSelected.has(currentRootParentKey)) {
            return;
        }
        if (selectedKeysSet.has(node.key)) {
            rootParentsSelected.add(currentRootParentKey);
        }
        if (node.children) {
            node.children.forEach((childNode)=>{
                dfs(childNode, currentRootParentKey);
            });
        }
    };
    if (node.children) {
        node.children.forEach((rootNode)=>{
            dfs(rootNode, rootNode.key);
        });
    }
    return rootParentsSelected;
};
const traverseTree = (items, selectedKeys)=>{
    const selectedKeysSet = new Set(selectedKeys);
    const copyItems = (0, _utils.deepCopy)(items);
    const rootParentsSelected = getRootParentsSelectedChildren({
        key: 'root',
        children: copyItems
    }, selectedKeysSet);
    copyItems.forEach((item)=>{
        dfs(item, selectedKeysSet, rootParentsSelected, [
            item
        ]);
    });
    return copyItems;
};
