"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Functional_1 = require("../../../../Class/Functional");
const bundle_1 = require("../../../../bundle");
const spec_1 = require("../../../../client/spec");
const fromBundle_1 = require("../../../../spec/fromBundle");
const spec_2 = require("../../../../spec/reducers/spec_");
const object_1 = require("../../../../util/object");
const weakMerge_1 = require("../../../../weakMerge");
const _ids_1 = require("../../../_ids");
class AddUnit0 extends Functional_1.Functional {
    constructor(system) {
        super({
            i: ['id', 'class', 'graph'],
            o: ['graph'],
        }, {}, system, _ids_1.ID_ADD_UNIT_0);
    }
    f({ id, class: Class, graph }, done) {
        var _a;
        let new_graph;
        try {
            const { __bundle } = Class;
            const { unit: __unit } = __bundle;
            const { id: __id, input: __inputs = {} } = __unit;
            const specs = (0, weakMerge_1.weakMerge)((_a = __bundle.specs) !== null && _a !== void 0 ? _a : {}, this.__system.specs);
            const unit_spec = (0, spec_1.getSpec)(specs, __id);
            const unit_graph_spec = { id: __id, input: {}, output: {} };
            const { inputs = {}, outputs = {} } = unit_spec;
            for (const inputId in inputs) {
                unit_graph_spec.input[inputId] = unit_graph_spec.input[inputId] || {};
                const __input = __inputs[inputId];
                if (__input) {
                    const { data } = __input;
                    unit_graph_spec.input[inputId].data = data;
                }
                const input = inputs[inputId];
                const { defaultIgnored } = input;
                if (defaultIgnored) {
                    unit_graph_spec.input[inputId].ignored = defaultIgnored;
                }
            }
            for (const outputId in outputs) {
                const output = outputs[outputId];
                const { defaultIgnored } = output;
                if (defaultIgnored) {
                    unit_graph_spec.output[outputId] =
                        unit_graph_spec.output[outputId] || {};
                    unit_graph_spec.output[outputId].ignored = defaultIgnored;
                }
            }
            const new_spec_id = (0, spec_1.newSpecId)(specs);
            const spec = (0, spec_1.getSpec)(specs, graph.__bundle.unit.id);
            const new_spec = (0, object_1.clone)(spec);
            new_spec.id = new_spec_id;
            (0, spec_2.addUnit)({ unitId: id, unit: unit_graph_spec }, new_spec);
            const new_bundle = (0, bundle_1.bundleSpec)(new_spec, specs);
            new_graph = (0, fromBundle_1.fromBundle)(new_bundle, specs, this.__system.classes);
        }
        catch (err) {
            done(undefined, err.message);
            return;
        }
        done({ graph: new_graph });
    }
}
exports.default = AddUnit0;
//# sourceMappingURL=index.js.map