text: "use strict";
  var __extends = (this && this.__extends) || (function () {
      var extendStatics = Object.setPrototypeOf ||
          ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
          function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return function (d, b) {
          extendStatics(d, b);
          function __() { this.constructor = d; }
          d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
      };
  })();
  var __assign = (this && this.__assign) || Object.assign || function(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
              t[p] = s[p];
      }
      return t;
  };
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  var __generator = (this && this.__generator) || function (thisArg, body) {
      var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
      function verb(n) { return function (v) { return step([n, v]); }; }
      function step(op) {
          if (f) throw new TypeError("Generator is already executing.");
          while (_) try {
              if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [0, t.value];
              switch (op[0]) {
                  case 0: case 1: t = op; break;
                  case 4: _.label++; return { value: op[1], done: false };
                  case 5: _.label++; y = op[1]; op = [0]; continue;
                  case 7: op = _.ops.pop(); _.trys.pop(); continue;
                  default:
                      if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                      if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                      if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                      if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                      if (t[2]) _.ops.pop();
                      _.trys.pop(); continue;
              }
              op = body.call(thisArg, _);
          } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
          if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
      }
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  /*
   * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
   * the License. A copy of the License is located at
   *
   *     http://aws.amazon.com/apache2.0/
   *
   * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
   * and limitations under the License.
   */
  var paho_mqtt_1 = require("paho-mqtt");
  var uuid_1 = require("uuid");
  var Observable = require("zen-observable");
  global.Paho = global.Paho || { MQTT: { Client: paho_mqtt_1.Client, Message: paho_mqtt_1.Message } };
  var PubSubProvider_1 = require("./PubSubProvider");
  var Logger_1 = require("../../Common/Logger");
  var logger = new Logger_1.ConsoleLogger('MqttOverWSProvider');
  var ClientsQueue = /** @class */ (function () {
      function ClientsQueue() {
          this.promises = new Map();
          this.map = new Map();
      }
      ClientsQueue.prototype.get = function (clientId, clientFactory) {
          return __awaiter(this, void 0, void 0, function () {
              var client, promise;
              return __generator(this, function (_a) {
                  client = this.map.get(clientId);
                  if (client) {
                      return [2 /*return*/, client];
                  }
                  promise = this.promises.get(clientId);
                  if (promise) {
                      return [2 /*return*/, promise];
                  }
                  promise = clientFactory(clientId);
                  this.promises.set(clientId, promise);
                  return [2 /*return*/, promise];
              });
          });
      };
      return ClientsQueue;
  }());
  var MqttOverWSProvider = /** @class */ (function (_super) {
      __extends(MqttOverWSProvider, _super);
      function MqttOverWSProvider(options) {
          if (options === void 0) { options = {}; }
          var _this = _super.call(this, __assign({}, options, { clientId: options.clientId || uuid_1.v4() })) || this;
          _this.clientsQueue = new ClientsQueue();
          _this._topicObservers = new Map();
          return _this;
      }
      Object.defineProperty(MqttOverWSProvider.prototype, "clientId", {
          get: function () { return this.options.clientId; },
          enumerable: true,
          configurable: true
      });
      Object.defineProperty(MqttOverWSProvider.prototype, "endpoint", {
          get: function () { return this.options.aws_pubsub_endpoint; },
          enumerable: true,
          configurable: true
      });
      MqttOverWSProvider.prototype.getProviderName = function () { return 'MqttOverWSProvider'; };
      MqttOverWSProvider.prototype.newClient = function (_a) {
          var url = _a.url, clientId = _a.clientId;
          return __awaiter(this, void 0, void 0, function () {
              var _this = this;
              var client;
              return __generator(this, function (_b) {
                  switch (_b.label) {
                      case 0:
                          logger.debug('Creating new MQTT client', clientId);
                          client = new paho_mqtt_1.Client(url, clientId);
                          // client.trace = (...args) => logger.debug(clientId, ...args);
                          client.onMessageArrived = function (_a) {
                              var topic = _a.destinationName, msg = _a.payloadString;
                              _this._onMessage(topic, msg);
                          };
                          client.onConnectionLost = logger.warn.bind(logger);
                          return [4 /*yield*/, new Promise(function (resolve, reject) {
                                  client.connect({
                                      useSSL: true,
                                      mqttVersion: 3,
                                      onSuccess: function () { return resolve(client); },
                                      onFailure: reject,
                                  });
                              })];
                      case 1:
                          _b.sent();
                          return [2 /*return*/, client];
                  }
              });
          });
      };
      MqttOverWSProvider.prototype.connect = function (clientId, options) {
          if (options === void 0) { options = {}; }
          return __awaiter(this, void 0, void 0, function () {
              var _this = this;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.clientsQueue.get(clientId, function (clientId) { return _this.newClient(__assign({}, options, { clientId: clientId })); })];
                      case 1: return [2 /*return*/, _a.sent()];
                  }
              });
          });
      };
      MqttOverWSProvider.prototype.publish = function (topics, msg) {
          return __awaiter(this, void 0, void 0, function () {
              var targetTopics, message, url, client;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          targetTopics = [].concat(topics);
                          message = JSON.stringify(msg);
                          return [4 /*yield*/, this.endpoint];
                      case 1:
                          url = _a.sent();
                          return [4 /*yield*/, this.connect(this.clientId, { url: url })];
                      case 2:
                          client = _a.sent();
                          logger.debug('Publishing to topic(s)', targetTopics.join(','), message);
                          targetTopics.forEach(function (topic) { return client.send(topic, message); });
                          return [2 /*return*/];
                  }
              });
          });
      };
      MqttOverWSProvider.prototype._onMessage = function (topic, msg) {
          try {
              var observersForTopic = this._topicObservers.get(topic) || new Set();
              var parsedMessage_1 = JSON.parse(msg);
              observersForTopic.forEach(function (observer) { return observer.next(parsedMessage_1); });
          }
          catch (error) {
              logger.warn('Error handling message', error, msg);
          }
      };
      MqttOverWSProvider.prototype.subscribe = function (topics, options) {
          var _this = this;
          if (options === void 0) { options = {}; }
          var targetTopics = [].concat(topics);
          logger.debug('Subscribing to topic(s)', targetTopics.join(','));
          return new Observable(function (observer) {
              targetTopics.forEach(function (topic) {
                  var observersForTopic = _this._topicObservers.get(topic);
                  if (!observersForTopic) {
                      observersForTopic = new Set();
                      _this._topicObservers.set(topic, observersForTopic);
                  }
                  observersForTopic.add(observer);
              });
              var client;
              (function () { return __awaiter(_this, void 0, void 0, function () {
                  var _a, url, _b, clientId, _c;
                  return __generator(this, function (_d) {
                      switch (_d.label) {
                          case 0:
                              _a = options.url;
                              if (!(_a === void 0)) return [3 /*break*/, 2];
                              return [4 /*yield*/, this.endpoint];
                          case 1:
                              _c = _d.sent();
                              return [3 /*break*/, 3];
                          case 2:
                              _c = _a;
                              _d.label = 3;
                          case 3:
                              url = _c, _b = options.clientId, clientId = _b === void 0 ? this.clientId : _b;
                              return [4 /*yield*/, this.connect(clientId, { url: url })];
                          case 4:
                              client = _d.sent();
                              targetTopics.forEach(function (topic) { return client.subscribe(topic); });
                              return [2 /*return*/];
                      }
                  });
              }); })();
              return function () {
                  logger.debug('Unsubscribing from topic(s)', targetTopics.join(','));
                  if (client) {
                      targetTopics.forEach(function (topic) {
                          client.unsubscribe(topic);
                      });
                  }
                  return null;
              };
          });
      };
      return MqttOverWSProvider;
  }(PubSubProvider_1.AbstractPubSubProvider));
  exports.MqttOverWSProvider = MqttOverWSProvider;
  //# sourceMappingURL=MqttOverWSProvider.js.map