"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var ROOT_TREE_NODE = 0;
exports.addItemToDict = function (item, dict) {
    var _a;
    var id = item.id;
    if (dict[id]) {
        throw new Error("Item with id " + id + " already in dict");
    }
    return __assign({}, dict, (_a = {}, _a[id] = item, _a));
};
exports.addItemToTree = function (item, tree, dict, root) {
    var _a;
    if (root === void 0) { root = ROOT_TREE_NODE; }
    var id = item.id, _b = item.parentId, parentId = _b === void 0 ? root : _b;
    if (!id || (!parentId && parentId !== root)) {
        throw new Error("Got invalid item data: " + item);
    }
    var parent = dict[parentId];
    if (parent && parent.parentId === id) {
        throw new Error("Cyclic structure detected: item " + id + " references " + parent.id);
    }
    var treeNode = tree[parentId] || [];
    return __assign({}, tree, (_a = {}, _a[parentId] = treeNode.concat([item]), _a));
};
exports.getItemByIdFromDict = function (id, dict) {
    return dict[id];
};
exports.getItemSiblingsFromTree = function (item, tree, root) {
    if (root === void 0) { root = ROOT_TREE_NODE; }
    if (!item) {
        return;
    }
    var parentId = item.parentId || root;
    return tree[parentId];
};
exports.getItemsChildrenFromTree = function (item, tree) {
    if (!item) {
        return;
    }
    var id = item.id;
    return tree[id];
};
exports.getRootNodeFromTree = function (tree, root) {
    if (root === void 0) { root = ROOT_TREE_NODE; }
    return tree[root];
};
exports.resolveItemPath = function (item, dict, path) {
    if (path === void 0) { path = []; }
    if (!item) {
        return;
    }
    var id = item.id, parentId = item.parentId;
    if (!id || !(id in dict)) {
        return;
    }
    var parent = dict[parentId];
    var nextPath = [id].concat(path);
    if (!parent) {
        return nextPath;
    }
    return exports.resolveItemPath(parent, dict, nextPath);
};
exports.resolveItemsMaxBranchLengthInTree = function (item, tree, resolvedLength) {
    if (resolvedLength === void 0) { resolvedLength = 0; }
    if (!item) {
        return resolvedLength;
    }
    var children = exports.getItemsChildrenFromTree(item, tree);
    if (children && children.length > 0) {
        var candidates = children.map(function (child) {
            return exports.resolveItemsMaxBranchLengthInTree(child, tree, resolvedLength + 1);
        });
        return Math.max.apply(Math, candidates);
    }
    return resolvedLength;
};
//# sourceMappingURL=TreeItemMap.js.map