"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("../constants");
/**
 * The MessageDistributor routes valid and permissioned messages to
 * various, previously registered handlers, e.g. event-, rpc- or recordHandler
 */
class MessageDistributor {
    constructor(options, services) {
        this.services = services;
        this.callbacks = new Map();
    }
    /**
     * Accepts a socketWrapper and a parsed message as input and distributes
     * it to its subscriber, based on the message's topic
     */
    distribute(socketWrapper, message) {
        const callback = this.callbacks.get(message.topic);
        if (callback === undefined) {
            this.services.logger.warn(constants_1.PARSER_ACTION[constants_1.PARSER_ACTION.UNKNOWN_TOPIC], constants_1.TOPIC[message.topic], { message });
            socketWrapper.sendMessage({
                topic: constants_1.TOPIC.PARSER,
                action: constants_1.PARSER_ACTION.UNKNOWN_TOPIC,
                originalTopic: message.topic
            });
            return;
        }
        this.services.monitoring.onMessageReceived(message);
        callback(socketWrapper, message);
    }
    /**
     * Allows handlers (event, rpc, record) to register for topics. Subscribes them
     * to both messages passed to the distribute method as well as messages received
     * from the messageConnector
     */
    registerForTopic(topic, callback) {
        if (this.callbacks.has(topic)) {
            throw new Error(`Callback already registered for topic ${topic}`);
        }
        this.callbacks.set(topic, callback);
        this.services.clusterNode.subscribe(topic, this.onMessageConnectorMessage.bind(this, callback));
    }
    /**
     * Whenever a message from the messageConnector is received it is passed
     * to the relevant handler, but with null instead of
     * a socketWrapper as sender
     */
    onMessageConnectorMessage(callback, message, originServer) {
        callback(null, message, originServer);
    }
}
exports.default = MessageDistributor;
//# sourceMappingURL=message-distributor.js.map