"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bundleSpec = exports.unitBundleSpecById = exports.unitBundleSpec = void 0;
const spec_1 = require("./client/spec");
function unitBundleSpec(unit, specs) {
    const { id } = unit;
    const spec = (0, spec_1.getSpec)(specs, id);
    const { system } = spec;
    if (system) {
        return {
            unit: Object.assign({ id }, unit),
        };
    }
    else {
        const custom = {
            [id]: spec,
        };
        _bundle(spec, specs, custom, new Set());
        return {
            unit: Object.assign({ id }, unit),
            specs: custom,
        };
    }
}
exports.unitBundleSpec = unitBundleSpec;
function unitBundleSpecById(id, specs) {
    const spec = (0, spec_1.getSpec)(specs, id);
    const { base } = spec;
    if (base) {
        return {
            unit: {
                id,
            },
        };
    }
    else {
        const custom = {
            [id]: spec,
        };
        _bundle(spec, specs, custom, new Set());
        return {
            unit: {
                id,
            },
            specs: custom,
        };
    }
}
exports.unitBundleSpecById = unitBundleSpecById;
function bundleSpec(spec, specs) {
    const custom = {};
    const branch = new Set([spec.id]);
    _bundle(spec, specs, custom, branch);
    return { spec, specs: custom };
}
exports.bundleSpec = bundleSpec;
function _bundle(spec, specs, custom, branch) {
    if (!spec.id) {
        throw new Error('Spec id is required.');
    }
    if (spec.system) {
        return;
    }
    if (!custom[spec.id] && !branch.has(spec.id)) {
        if (!specs[spec.id] || !(0, spec_1.isSystemSpecId)(specs, spec.id)) {
            custom[spec.id] = spec;
        }
    }
    branch.add(spec.id);
    _bundleUnits(spec, specs, custom, branch);
}
function _bundleUnits(spec, specs, custom, branch) {
    const { units = {} } = spec;
    for (const unit_id in units) {
        const unit = units[unit_id];
        const { id } = unit;
        const _spec = (0, spec_1.getSpec)(specs, id);
        _bundle(_spec, specs, custom, new Set(branch));
    }
}
//# sourceMappingURL=bundle.js.map