"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.watchGraphComponent = void 0;
const callAll_1 = require("../../util/call/callAll");
const componentFromUnitSpec_1 = require("../componentFromUnitSpec");
const component_1 = require("../component_");
function watchGraphComponent(system, $graph, component) {
    const unlisten_component = () => {
        // component._disconnect()
    };
    const unlisten_sub_component = (sub_component_id) => {
        const sub_component_unlisten = _sub_component_unlisten[sub_component_id];
        sub_component_unlisten();
        delete _sub_component_unlisten[sub_component_id];
    };
    const _sub_component_unlisten = {};
    const unlisten_sub_components = () => {
        for (const sub_component_id in _sub_component_unlisten) {
            unlisten_sub_component(sub_component_id);
        }
    };
    const listen_sub_component = (unitId, sub_component) => {
        const _ = (0, component_1.getComponentInterface)(sub_component);
        const sub_component_async_ref = $graph.$refSubComponent({ unitId, _ });
        const sub_component_unlisten = watchGraphComponent(system, sub_component_async_ref, sub_component);
        _sub_component_unlisten[unitId] = sub_component_unlisten;
    };
    if (component.$unbundled) {
        for (const sub_component_id in component.$subComponent) {
            const sub_component = component.getSubComponent(sub_component_id);
            listen_sub_component(sub_component_id, sub_component);
        }
    }
    const unlisten_graph = $graph.$watch({ events: ['component_append', 'component_remove'] }, (moment) => {
        const { type, event, data } = moment;
        const handler = {
            component_append: (data) => {
                const { unitId, unitSpec } = data;
                const sub_component = (0, componentFromUnitSpec_1.componentFromUnitSpec)(system, system.specs, unitSpec);
                component.setSubComponent(unitId, sub_component);
                component.appendRoot(sub_component);
                listen_sub_component(unitId, sub_component);
            },
            component_remove: (data) => {
                const { unitId } = data;
                unlisten_sub_component(unitId);
                const sub_component = component.removeSubComponent(unitId);
                component.removeRoot(sub_component);
            },
        };
        handler[event](data);
    });
    const unlisten = (0, callAll_1.callAll)([
        unlisten_component,
        unlisten_graph,
        unlisten_sub_components,
    ]);
    return unlisten;
}
exports.watchGraphComponent = watchGraphComponent;
//# sourceMappingURL=watchGraphComponent.js.map