"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blockHasChildrenProp = blockHasChildrenProp;
exports.getBlockTypeLabel = getBlockTypeLabel;
exports.getBlockChildren = getBlockChildren;
exports.blocksToTreeItems = blocksToTreeItems;
exports.treeItemsToBlocks = treeItemsToBlocks;
exports.idToBlockPath = idToBlockPath;
const tslib_1 = require("tslib");
/* eslint-disable no-negated-condition */
const lodash_1 = tslib_1.__importDefault(require("lodash"));
function blockHasChildrenProp(block) {
    return Boolean(block && typeof block === 'object' && 'children' in block);
}
function getBlockTypeLabel(block) {
    if (block && typeof block === 'object' && 'type' in block) {
        return block.type;
    }
    return '';
}
function getBlockChildren(block) {
    if (block && typeof block === 'object' && 'children' in block) {
        if (Array.isArray(block.children)) {
            return block.children;
        }
    }
    return undefined;
}
function blocksToTreeItems(blocks, pathPrefix = '') {
    return blocks.map((block, index) => {
        const id = pathPrefix ? `${pathPrefix}/${index}` : String(index);
        const children = getBlockChildren(block);
        return {
            id,
            block,
            children: children ? blocksToTreeItems(children, id) : [],
        };
    });
}
function treeItemsToBlocks(items) {
    return items.map((item) => {
        const next = lodash_1.default.cloneDeep(item.block);
        const nested = treeItemsToBlocks(item.children);
        if (nested.length > 0) {
            next.children = nested;
        }
        else if (getBlockChildren(item.block) !== undefined) {
            next.children = [];
        }
        return next;
    });
}
// Путь индексов от корня; при цикле или разрыве связи — пустой массив.
function idToBlockPath(flat, id) {
    const byId = new Map(flat.map((x) => [String(x.id), x]));
    const path = [];
    const seen = new Set();
    let currentId = String(id);
    const maxSteps = flat.length + 1;
    for (let step = 0; step < maxSteps && currentId !== null; step++) {
        if (seen.has(currentId)) {
            return [];
        }
        seen.add(currentId);
        const row = byId.get(currentId);
        if (!row) {
            return [];
        }
        path.unshift(row.index);
        const p = row.parentId;
        currentId = p === null ? null : String(p);
    }
    return currentId !== null ? [] : path;
}
//# sourceMappingURL=blocksBridge.js.map
