"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dataBridge = void 0;
const WebSocket = require("ws");
const shell_1 = require("@things-factory/shell");
const debug = require('debug')('aidoop:data-bridge');
class DataBridge {
    constructor(portExt) {
        this.portExt = portExt;
    }
    start() {
        if (!this.wssExt) {
            this.wssExt = new WebSocket.Server({ port: this.portExt });
        }
        this.wssExt.on('connection', ws => {
            ws.on('message', message => {
                this.sendToClient(message.toString());
            });
            ws.on('error', error => {
                debug('recv. error from ext. module');
            });
        });
    }
    sendToExt(message) {
        this.wssExt.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                try {
                    client.send(message);
                }
                catch (e) {
                    debug('sendToExt');
                    debug(e.name + ':' + e.message);
                }
            }
        });
    }
    sendCmdToExt(cmd, name) {
        const message = {
            type: 'cmd',
            name: name,
            body: cmd
        };
        this.sendToExt(JSON.stringify(message));
    }
    sendToClient(message) {
        try {
            var { name, body } = JSON.parse(message);
            shell_1.pubsub.publish('data', {
                data: {
                    domain: { subdomain: 'system' },
                    tag: name,
                    data: body
                }
            });
        }
        catch (e) {
            debug(`sendToClient errior: ${e.name} : ${e.message}`);
        }
    }
}
exports.dataBridge = new DataBridge(34000);
//# sourceMappingURL=data-bridge.js.map