"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dist_1 = require("@leftshiftone/gaia-sdk/dist");
var EventStream_1 = require("../event/EventStream");
var Subscription_1 = require("./Subscription");
var Connection = /** @class */ (function () {
    function Connection(options, renderer, listener) {
        this.subscriptions = new Map();
        this.mqttSensorQueue = this.initMqttSensorQueue(options);
        this.renderer = renderer;
        this.listener = listener;
    }
    /**
     * Subscribes to the given destination.
     *
     * @param type the queue type
     * @param header the destination header
     * @param callback the callback function
     */
    Connection.prototype.subscribe = function (type, header, callback) {
        var subscription = new Subscription_1.Subscription(type, header, callback, this.mqttSensorQueue, this.renderer);
        this.subscriptions.set(this.mqttSensorQueue.getTopic(type, header), subscription);
        return subscription;
    };
    /**
     * disconnect the mqtt connection
     */
    Connection.prototype.disconnect = function () {
        var _this = this;
        EventStream_1.default.removeAllListeners();
        this.subscriptions.forEach(function (subscription) { return subscription.unsubscribe(); });
        this.mqttSensorQueue.end(false, function () { return _this.listener.onDisconnected(); });
    };
    Connection.prototype.initMqttSensorQueue = function (options) {
        var _this = this;
        var mqttSensorQueue = new dist_1.MqttSensorQueue(options);
        mqttSensorQueue.on('packetsend', function (packet) { return _this.listener.onPacketSend(packet); });
        mqttSensorQueue.on('message', function (topic, message) { return _this.onMessage(topic, message); });
        mqttSensorQueue.on('connect', function () { return _this.listener.onConnected(); });
        mqttSensorQueue.on('offline', function () { return _this.listener.onConnectionLost(); });
        return mqttSensorQueue;
    };
    Connection.prototype.onMessage = function (topic, message) {
        var payload = JSON.parse(message);
        this.listener.onMessage(payload);
        this.subscriptions.get(topic).onMessage(payload);
    };
    return Connection;
}());
exports.Connection = Connection;
//# sourceMappingURL=Connection.js.map