"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapToTree = void 0;
const node_1 = require("./node");
const mapToTree = (record) => {
    function dfs(list, parentId) {
        const result = [];
        list.forEach((item) => {
            var _a;
            let children = item.children || [];
            const childIds = (item.childIds || []).filter((item) => children.findIndex((child) => child.id === item) === -1);
            if (childIds.length > 0) {
                children = children.concat(childIds === null || childIds === void 0 ? void 0 : childIds.map((id) => record[id]).filter((it) => !!it));
            }
            let node = (0, node_1.pickNode)(item);
            node = Object.assign(Object.assign({}, node), { extension: Object.assign(Object.assign({}, node.extension), { parentId: ((_a = node.extension) === null || _a === void 0 ? void 0 : _a.parentId) || parentId }), children: children.length > 0 ? dfs(children, node.id) : [] });
            result.push(node);
        });
        return result.sort((a, b) => (a.extension.sort || 0) - (b.extension.sort || 0));
    }
    const tree = dfs(Object.values(record).filter((item) => { var _a; return !record[((_a = item.extension) === null || _a === void 0 ? void 0 : _a.parentId) || '']; }), '');
    return tree;
};
exports.mapToTree = mapToTree;
