"use strict";

var _typeof = require("@babel/runtime-corejs2/helpers/typeof");
var _Reflect$construct = require("@babel/runtime-corejs2/core-js/reflect/construct");
var _Array$from = require("@babel/runtime-corejs2/core-js/array/from");
var _Symbol = require("@babel/runtime-corejs2/core-js/symbol");
var _Symbol$iterator = require("@babel/runtime-corejs2/core-js/symbol/iterator");
var _Array$isArray = require("@babel/runtime-corejs2/core-js/array/is-array");
var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.createClient = exports.CallingClient = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _values = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/values"));
var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));
var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/toConsumableArray"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var Media = _interopRequireWildcard(require("@webex/internal-media-core"));
var _asyncMutex = require("async-mutex");
var _constants = require("../common/constants");
var _Utils = require("../common/Utils");
var _types = require("../Logger/types");
var _SDKConnector = _interopRequireDefault(require("../SDKConnector"));
var _impl = require("../Events/impl");
var _types2 = require("../Events/types");
var _types3 = require("../common/types");
var _types4 = require("./calling/types");
var _Logger = _interopRequireDefault(require("../Logger"));
var _callManager = require("./calling/callManager");
var _constants2 = require("./constants");
var _line = _interopRequireDefault(require("./line"));
var _types5 = require("../Metrics/types");
var _Metrics = require("../Metrics");
var _windowsChromiumIceWarmupUtils = _interopRequireDefault(require("./windowsChromiumIceWarmupUtils"));
var _request = require("./utils/request");
function _interopRequireWildcard(e, t) { if ("function" == typeof _WeakMap) var r = new _WeakMap(), n = new _WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t11 in e) "default" !== _t11 && {}.hasOwnProperty.call(e, _t11) && ((i = (o = _Object$defineProperty) && _Object$getOwnPropertyDescriptor(e, _t11)) && (i.get || i.set) ? o(f, _t11, i) : f[_t11] = e[_t11]); return f; })(e, t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && r[_Symbol$iterator] || r["@@iterator"]; if (!t) { if (_Array$isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /* eslint-disable no-underscore-dangle */ /* eslint-disable valid-jsdoc */ /* eslint-disable @typescript-eslint/no-shadow */
/**
 * The `CallingClient` module provides a set of APIs for line registration and calling functionalities within the SDK.
 *
 * The following code snippet demonstrates how to create an instance of `CallingClient` using a `webex` instance and `callingConfig`:
 *
 * @example
 * ```javascript
 * const callingClient = createClient(webex, callingConfig);
 * ```
 */
var CallingClient = exports.CallingClient = /*#__PURE__*/function (_Eventing) {
  /**
   * @ignore
   */
  function CallingClient(webex, config) {
    var _this$sdkConfig, _this$sdkConfig$servi, _this$sdkConfig2, _this$sdkConfig2$logg;
    var _this;
    (0, _classCallCheck2.default)(this, CallingClient);
    _this = _callSuper(this, CallingClient);
    (0, _defineProperty2.default)(_this, "sdkConnector", void 0);
    (0, _defineProperty2.default)(_this, "webex", void 0);
    (0, _defineProperty2.default)(_this, "mutex", void 0);
    (0, _defineProperty2.default)(_this, "callManager", void 0);
    (0, _defineProperty2.default)(_this, "metricManager", void 0);
    (0, _defineProperty2.default)(_this, "sdkConfig", void 0);
    (0, _defineProperty2.default)(_this, "serviceData", void 0);
    (0, _defineProperty2.default)(_this, "primaryMobiusUris", void 0);
    (0, _defineProperty2.default)(_this, "backupMobiusUris", void 0);
    (0, _defineProperty2.default)(_this, "primaryWssMobiusUris", void 0);
    (0, _defineProperty2.default)(_this, "backupWssMobiusUris", void 0);
    (0, _defineProperty2.default)(_this, "mobiusClusters", void 0);
    (0, _defineProperty2.default)(_this, "mobiusHost", void 0);
    (0, _defineProperty2.default)(_this, "mediaEngine", void 0);
    (0, _defineProperty2.default)(_this, "lineDict", {});
    (0, _defineProperty2.default)(_this, "apiRequest", void 0);
    (0, _defineProperty2.default)(_this, "isNetworkDown", false);
    (0, _defineProperty2.default)(_this, "networkDownTimestamp", '');
    (0, _defineProperty2.default)(_this, "networkUpTimestamp", '');
    (0, _defineProperty2.default)(_this, "mercuryDownTimestamp", '');
    (0, _defineProperty2.default)(_this, "mercuryUpTimestamp", '');
    (0, _defineProperty2.default)(_this, "handleNetworkOffline", /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
      var line;
      return _regenerator.default.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _this.networkDownTimestamp = new Date().toISOString();
            _context.next = 1;
            return _this.checkNetworkReachability();
          case 1:
            _this.isNetworkDown = !_context.sent;
            _Logger.default.warn("Network has gone down, wait for it to come back up", {
              file: _constants2.CALLING_CLIENT_FILE,
              method: _constants2.METHODS.NETWORK_OFFLINE
            });
            if (_this.isNetworkDown) {
              line = (0, _values.default)(_this.lineDict)[0];
              line.registration.clearKeepaliveTimer();
            }
          case 2:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    // Wondering if we should keep this for timestamp recording purpose
    (0, _defineProperty2.default)(_this, "handleNetworkOnline", function () {
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.CALLING_CLIENT_FILE,
        method: _constants2.METHODS.NETWORK_ONLINE
      });
      _this.networkUpTimestamp = new Date().toISOString();
    });
    (0, _defineProperty2.default)(_this, "handleMercuryOffline", function () {
      _Logger.default.warn("Mercury down, waiting for connection to be up", {
        file: _constants2.CALLING_CLIENT_FILE,
        method: _constants2.METHODS.MERCURY_OFFLINE
      });
      _this.mercuryDownTimestamp = new Date().toISOString();
      _this.metricManager.submitConnectionMetrics(_types5.METRIC_EVENT.CONNECTION_ERROR, _types5.CONNECTION_ACTION.MERCURY_DOWN, _types5.METRIC_TYPE.BEHAVIORAL, _this.mercuryDownTimestamp, _this.mercuryUpTimestamp);
    });
    (0, _defineProperty2.default)(_this, "handleMercuryOnline", /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
      var callCheckInterval;
      return _regenerator.default.wrap(function (_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _Logger.default.info(_constants.METHOD_START_MESSAGE, {
              file: _constants2.CALLING_CLIENT_FILE,
              method: _constants2.METHODS.MERCURY_ONLINE
            });
            _this.mercuryUpTimestamp = new Date().toISOString();
            if (!_this.isNetworkDown) {
              _context3.next = 2;
              break;
            }
            callCheckInterval = setInterval(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
              var line;
              return _regenerator.default.wrap(function (_context2) {
                while (1) switch (_context2.prev = _context2.next) {
                  case 0:
                    if ((0, _keys.default)(_this.callManager.getActiveCalls()).length) {
                      _context2.next = 3;
                      break;
                    }
                    clearInterval(callCheckInterval);
                    line = (0, _values.default)(_this.lineDict)[0];
                    if (!(line.getStatus() !== _types3.RegistrationStatus.IDLE)) {
                      _context2.next = 2;
                      break;
                    }
                    _context2.next = 1;
                    return line.registration.handleConnectionRestoration(_this.isNetworkDown);
                  case 1:
                    _this.isNetworkDown = _context2.sent;
                    _context2.next = 3;
                    break;
                  case 2:
                    _this.isNetworkDown = false;
                  case 3:
                  case "end":
                    return _context2.stop();
                }
              }, _callee2);
            })), _constants2.NETWORK_FLAP_TIMEOUT);
            if (!(0, _keys.default)(_this.callManager.getActiveCalls()).length) {
              _context3.next = 1;
              break;
            }
            _context3.next = 1;
            return _this.checkCallStatus();
          case 1:
            _this.metricManager.submitConnectionMetrics(_types5.METRIC_EVENT.CONNECTION_ERROR, _types5.CONNECTION_ACTION.NETWORK_FLAP, _types5.METRIC_TYPE.BEHAVIORAL, _this.networkDownTimestamp, _this.networkUpTimestamp);
            _context3.next = 4;
            break;
          case 2:
            if (!(0, _keys.default)(_this.callManager.getActiveCalls()).length) {
              _context3.next = 3;
              break;
            }
            _context3.next = 3;
            return _this.checkCallStatus();
          case 3:
            _this.metricManager.submitConnectionMetrics(_types5.METRIC_EVENT.CONNECTION_ERROR, _types5.CONNECTION_ACTION.MERCURY_UP, _types5.METRIC_TYPE.BEHAVIORAL, _this.mercuryDownTimestamp, _this.mercuryUpTimestamp);
          case 4:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    (0, _defineProperty2.default)(_this, "handleMobiusAsyncEvent", /*#__PURE__*/function () {
      var _ref4 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4(event) {
        var loggerContext, eventType, line;
        return _regenerator.default.wrap(function (_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              loggerContext = {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.HANDLE_MOBIUS_ASYNC_EVENT
              };
              eventType = event === null || event === void 0 ? void 0 : event.data.eventType;
              _Logger.default.trace("Mobius async event received - eventType: ".concat(eventType !== null && eventType !== void 0 ? eventType : 'undefined'), loggerContext);
              if (eventType) {
                _context4.next = 1;
                break;
              }
              _Logger.default.warn('Dropping unsupported mobius socket payload', loggerContext);
              return _context4.abrupt("return");
            case 1:
              if (!(eventType === _types4.MobiusEventType.REGISTRATION_DOWN)) {
                _context4.next = 4;
                break;
              }
              _Logger.default.warn("Received ".concat(eventType, " event from Mobius."), loggerContext);
              line = (0, _values.default)(_this.lineDict)[0];
              if (line) {
                _context4.next = 2;
                break;
              }
              _Logger.default.warn('No line found, skipping registration down event', loggerContext);
              return _context4.abrupt("return");
            case 2:
              _context4.next = 3;
              return line.registration.handleRegistrationDownEvent(event);
            case 3:
              _this.metricManager.submitMobiusSocketMetric(_types5.METRIC_EVENT.MOBIUS_SOCKET_ERROR, _types5.MOBIUS_SOCKET_ACTION.REGISTRATION_DOWN, _types5.METRIC_TYPE.BEHAVIORAL, undefined, event === null || event === void 0 ? void 0 : event.trackingId, undefined, eventType);
              return _context4.abrupt("return");
            case 4:
              _this.callManager.dequeueWsEvents(event);
              _Logger.default.trace("Mobius async event dispatched to CallManager - eventType: ".concat(eventType), loggerContext);
            case 5:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function (_x) {
        return _ref4.apply(this, arguments);
      };
    }());
    /**
     * Handler registered for ALL_CALLS_CLEARED event emitted by callManager.
     *
     * If re-register attempt was deferred earlier due to active call(s), then it
     * will be attempted here on receiving a notification from callManager that all
     * calls are cleaned up.
     */
    (0, _defineProperty2.default)(_this, "callsClearedHandler", /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee6() {
      var registration;
      return _regenerator.default.wrap(function (_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            _Logger.default.info(_constants.METHOD_START_MESSAGE, {
              file: _constants2.CALLING_CLIENT_FILE,
              method: _constants2.METHODS.CALLS_CLEARED_HANDLER
            });
            // this is a temporary logic to get registration obj
            // it will change once we have proper lineId and multiple lines as well
            registration = (0, _values.default)(_this.lineDict)[0].registration;
            if (registration.isDeviceRegistered()) {
              _context6.next = 1;
              break;
            }
            _context6.next = 1;
            return _this.mutex.runExclusive(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee5() {
              return _regenerator.default.wrap(function (_context5) {
                while (1) switch (_context5.prev = _context5.next) {
                  case 0:
                    if (!registration.isReconnectPending()) {
                      _context5.next = 1;
                      break;
                    }
                    _Logger.default.info('All calls cleared, reconnecting', {
                      file: _constants2.CALLING_CLIENT_FILE,
                      method: _constants2.CALLS_CLEARED_HANDLER_UTIL
                    });
                    _context5.next = 1;
                    return registration.reconnectOnFailure(_constants2.CALLS_CLEARED_HANDLER_UTIL);
                  case 1:
                  case "end":
                    return _context5.stop();
                }
              }, _callee5);
            })));
          case 1:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    })));
    _this.sdkConnector = _SDKConnector.default;
    if (!_this.sdkConnector.getWebex()) {
      var _config$logger;
      _SDKConnector.default.setWebex(webex);
      if (config !== null && config !== void 0 && (_config$logger = config.logger) !== null && _config$logger !== void 0 && _config$logger.level && webex.logger.config) {
        webex.logger.config.level = config.logger.level; // override the webex logger level
      }
      _Logger.default.setWebexLogger(webex.logger);
    }
    _this.mutex = new _asyncMutex.Mutex();
    _this.webex = _this.sdkConnector.getWebex();
    _this.sdkConfig = config;
    _this.serviceData = (_this$sdkConfig = _this.sdkConfig) !== null && _this$sdkConfig !== void 0 && (_this$sdkConfig$servi = _this$sdkConfig.serviceData) !== null && _this$sdkConfig$servi !== void 0 && _this$sdkConfig$servi.indicator ? _this.sdkConfig.serviceData : {
      indicator: _types3.ServiceIndicator.CALLING,
      domain: ''
    };
    var logLevel = (_this$sdkConfig2 = _this.sdkConfig) !== null && _this$sdkConfig2 !== void 0 && (_this$sdkConfig2$logg = _this$sdkConfig2.logger) !== null && _this$sdkConfig2$logg !== void 0 && _this$sdkConfig2$logg.level ? _this.sdkConfig.logger.level : _types.LOGGER.ERROR;
    _Logger.default.setLogger(logLevel, _constants2.CALLING_CLIENT_FILE);
    (0, _Utils.validateServiceData)(_this.serviceData);
    _this.callManager = (0, _callManager.getCallManager)(_this.webex, _this.serviceData.indicator);
    _this.metricManager = (0, _Metrics.getMetricManager)(_this.webex, _this.serviceData.indicator);
    _this.mediaEngine = Media;
    var adaptedLogger = {
      log: function log() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        return webex.logger.log(args.join(' : '));
      },
      error: function error() {
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        return webex.logger.error(args.join(' : '));
      },
      warn: function warn() {
        for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
          args[_key3] = arguments[_key3];
        }
        return webex.logger.warn(args.join(' : '));
      },
      info: function info() {
        for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
          args[_key4] = arguments[_key4];
        }
        return webex.logger.info(args.join(' : '));
      },
      trace: function trace() {
        for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
          args[_key5] = arguments[_key5];
        }
        return webex.logger.trace(args.join(' : '));
      },
      debug: function debug() {
        for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
          args[_key6] = arguments[_key6];
        }
        return webex.logger.debug(args.join(' : '));
      }
    };
    _this.mediaEngine.setLogger(adaptedLogger);
    _this.primaryMobiusUris = [];
    _this.backupMobiusUris = [];
    _this.primaryWssMobiusUris = [];
    _this.backupWssMobiusUris = [];
    _this.mobiusClusters = _this.webex.internal.services.getMobiusClusters();
    _this.mobiusHost = '';
    _this.apiRequest = _request.APIRequest.getInstance({
      webex: _this.webex
    });
    _this.registerSessionsListener();
    _this.registerCallsClearedListener();
    return _this;
  }

  /**
   * Initializes the `CallingClient` by performing the following steps:
   *
   * 1. Retrieves list of servers.
   * 2. Creates a line.
   * 3. Sets up network change detection.
   *
   * This method should be called once to initialize the `callingClient`.
   *
   * @returns A promise that resolves when the initialization is complete.
   * @ignore
   */
  (0, _inherits2.default)(CallingClient, _Eventing);
  return (0, _createClass2.default)(CallingClient, [{
    key: "init",
    value: (function () {
      var _init = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee7() {
        var _window, _window$navigator;
        var loggerContext, ua, _this$sdkConfig3, rtmsDomain, _t;
        return _regenerator.default.wrap(function (_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              loggerContext = {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.INIT
              };
              _Logger.default.info(_constants.METHOD_START_MESSAGE, loggerContext);

              // Only for Windows Chromium based browsers we need to do the ICE warmup
              if (!(typeof window !== 'undefined' && (_window = window) !== null && _window !== void 0 && (_window$navigator = _window.navigator) !== null && _window$navigator !== void 0 && _window$navigator.userAgent)) {
                _context7.next = 4;
                break;
              }
              ua = window.navigator.userAgent;
              if (!ua.toLowerCase().includes('windows')) {
                _context7.next = 4;
                break;
              }
              _Logger.default.info('Starting ICE warmup for Windows Chromium based browser', {
                file: _constants2.CALLING_CLIENT_FILE,
                method: 'init'
              });
              _context7.prev = 1;
              _context7.next = 2;
              return (0, _windowsChromiumIceWarmupUtils.default)({
                iceServers: [],
                timeoutMs: 1000
              });
            case 2:
              _Logger.default.info("ICE warmup completed", {
                file: _constants2.CALLING_CLIENT_FILE,
                method: 'init'
              });
              _context7.next = 4;
              break;
            case 3:
              _context7.prev = 3;
              _t = _context7["catch"](1);
              _Logger.default.warn("ICE warmup failed: ".concat(_t), {
                file: _constants2.CALLING_CLIENT_FILE,
                method: 'init'
              });
            case 4:
              _context7.next = 5;
              return this.getMobiusServers();
            case 5:
              if (!this.apiRequest.isSocketEnabled()) {
                _context7.next = 7;
                break;
              }
              _context7.next = 6;
              return this.connectToMobiusSocket();
            case 6:
              this.apiRequest.registerMobiusSocketListener(this.handleMobiusAsyncEvent);
            case 7:
              // Auto-fetch RTMS domain from service catalog for contact-center flows
              if (this.serviceData.indicator === _types3.ServiceIndicator.CONTACT_CENTER && !this.serviceData.domain) {
                rtmsDomain = this.getRTMSDomain();
                this.serviceData.domain = rtmsDomain;
                if ((_this$sdkConfig3 = this.sdkConfig) !== null && _this$sdkConfig3 !== void 0 && _this$sdkConfig3.serviceData) {
                  this.sdkConfig.serviceData.domain = this.serviceData.domain;
                }
              }
              if ((0, _Utils.isValidServiceDomain)(this.serviceData)) {
                _context7.next = 8;
                break;
              }
              throw new Error('Invalid service domain.');
            case 8:
              _context7.next = 9;
              return this.createLine();
            case 9:
              this.setupNetworkEventListeners();
              _Logger.default.log('CallingClient initialization complete', loggerContext);
            case 10:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this, [[1, 3]]);
      }));
      function init() {
        return _init.apply(this, arguments);
      }
      return init;
    }()
    /**
     * Retrieves the RTMS domain from the service catalog for contact-center flows.
     *
     * @returns The RTMS domain from catalog when available.
     */
    )
  }, {
    key: "getRTMSDomain",
    value: function getRTMSDomain() {
      _Logger.default.info('Fetching RTMS domain from service catalog', {
        file: _constants2.CALLING_CLIENT_FILE,
        method: _constants2.METHODS.GET_RTMS_DOMAIN
      });
      try {
        var rtmsURL = this.webex.internal.services.get(_constants2.WCC_CALLING_RTMS_DOMAIN);
        var url = new URL(rtmsURL);
        _Logger.default.info("RTMS domain resolved from catalog: ".concat(url.hostname), {
          file: _constants2.CALLING_CLIENT_FILE,
          method: _constants2.METHODS.GET_RTMS_DOMAIN
        });
        return url.hostname;
      } catch (error) {
        _Logger.default.warn("Failed to fetch RTMS domain from service catalog: ".concat(error), {
          file: _constants2.CALLING_CLIENT_FILE,
          method: _constants2.METHODS.GET_RTMS_DOMAIN
        });
        return '';
      }
    }

    /**
     * Ping a reliable external endpoint with a short timeout to infer connectivity.
     */
  }, {
    key: "checkNetworkReachability",
    value: (function () {
      var _checkNetworkReachability = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee8() {
        var controller, timeoutId, _t2;
        return _regenerator.default.wrap(function (_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              _context8.prev = 0;
              controller = new AbortController();
              timeoutId = setTimeout(function () {
                return controller.abort();
              }, 3000); // Using a common connectivity check endpoint that returns 204 with minimal payload.
              // no-cors mode yields an opaque response but a successful fetch implies reachability.
              _context8.next = 1;
              return fetch('https://www.google.com/generate_204', {
                method: 'GET',
                cache: 'no-cache',
                mode: 'no-cors',
                signal: controller.signal
              });
            case 1:
              clearTimeout(timeoutId);
              return _context8.abrupt("return", true);
            case 2:
              _context8.prev = 2;
              _t2 = _context8["catch"](0);
              _Logger.default.warn("Network connectivity probe failed: ".concat(_t2), {
                file: _constants2.CALLING_CLIENT_FILE,
                method: 'pingExternal'
              });
              return _context8.abrupt("return", false);
            case 3:
            case "end":
              return _context8.stop();
          }
        }, _callee8, null, [[0, 2]]);
      }));
      function checkNetworkReachability() {
        return _checkNetworkReachability.apply(this, arguments);
      }
      return checkNetworkReachability;
    }())
  }, {
    key: "checkCallStatus",
    value: function () {
      var _checkCallStatus = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee9() {
        var loggerContext, calls, _iterator, _step, _loop, _t3;
        return _regenerator.default.wrap(function (_context0) {
          while (1) switch (_context0.prev = _context0.next) {
            case 0:
              loggerContext = {
                file: _constants2.CALLING_CLIENT_FILE,
                method: 'checkCallStatus'
              };
              calls = (0, _values.default)(this.callManager.getActiveCalls());
              _iterator = _createForOfIteratorHelper(calls);
              _context0.prev = 1;
              _loop = /*#__PURE__*/_regenerator.default.mark(function _loop() {
                var call;
                return _regenerator.default.wrap(function (_context9) {
                  while (1) switch (_context9.prev = _context9.next) {
                    case 0:
                      call = _step.value;
                      call.postStatus().then(function () {
                        _Logger.default.info("Call is active", loggerContext);
                        /*
                         * Media Renegotiation Possibility if call keepalive succeeds,
                         * for cases like WebRTC disconnect and media inactivity.
                         */
                      }).catch(function (err) {
                        _Logger.default.warn("Call Keepalive failed: ".concat(err), loggerContext);
                        call.sendCallStateMachineEvt({
                          type: 'E_SEND_CALL_DISCONNECT'
                        });
                      });
                    case 1:
                    case "end":
                      return _context9.stop();
                  }
                }, _loop);
              });
              _iterator.s();
            case 2:
              if ((_step = _iterator.n()).done) {
                _context0.next = 4;
                break;
              }
              return _context0.delegateYield(_loop(), "t0", 3);
            case 3:
              _context0.next = 2;
              break;
            case 4:
              _context0.next = 6;
              break;
            case 5:
              _context0.prev = 5;
              _t3 = _context0["catch"](1);
              _iterator.e(_t3);
            case 6:
              _context0.prev = 6;
              _iterator.f();
              return _context0.finish(6);
            case 7:
            case "end":
              return _context0.stop();
          }
        }, _callee9, this, [[1, 5, 6, 7]]);
      }));
      function checkCallStatus() {
        return _checkCallStatus.apply(this, arguments);
      }
      return checkCallStatus;
    }()
  }, {
    key: "setupNetworkEventListeners",
    value: function setupNetworkEventListeners() {
      var _this2 = this;
      if (typeof window !== 'undefined' && window.addEventListener) {
        window.addEventListener('online', this.handleNetworkOnline);
        window.addEventListener('offline', this.handleNetworkOffline);
      }
      this.webex.internal.mercury.on('offline', function () {
        _this2.handleMercuryOffline();
      });
      this.webex.internal.mercury.on('online', function () {
        _this2.handleMercuryOnline();
      });
    }

    /**
     * Fetches countryCode and region of the client.
     */
  }, {
    key: "getClientRegionInfo",
    value: (function () {
      var _getClientRegionInfo = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee0() {
        var _this3 = this;
        var abort, regionInfo, _response$headers, _response$headers$tra, _response$headers2, response, clientRegionInfo, _t4;
        return _regenerator.default.wrap(function (_context1) {
          while (1) switch (_context1.prev = _context1.next) {
            case 0:
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.GET_CLIENT_REGION_INFO
              });
              regionInfo = {};
              _context1.prev = 1;
              _context1.next = 2;
              return this.webex.request({
                uri: "".concat(_constants2.DISCOVERY_URL),
                method: _types3.HTTP_METHODS.GET,
                addAuthHeader: false,
                headers: (0, _defineProperty2.default)({}, _constants2.SPARK_USER_AGENT, null)
              });
            case 2:
              response = _context1.sent;
              clientRegionInfo = response.body;
              regionInfo.clientRegion = (clientRegionInfo === null || clientRegionInfo === void 0 ? void 0 : clientRegionInfo.clientRegion) || '';
              regionInfo.countryCode = (clientRegionInfo === null || clientRegionInfo === void 0 ? void 0 : clientRegionInfo.countryCode) || '';
              _Logger.default.log("Successfully fetched Client region info: ".concat(regionInfo.clientRegion, ", countryCode: ").concat(regionInfo.countryCode, ", and response trackingid: ").concat(response === null || response === void 0 ? void 0 : (_response$headers = response.headers) === null || _response$headers === void 0 ? void 0 : _response$headers.trackingid), {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.GET_CLIENT_REGION_INFO
              });
              this.metricManager.submitRegionInfoMetric(_types5.METRIC_EVENT.MOBIUS_DISCOVERY, _types5.MOBIUS_SERVER_ACTION.REGION_INFO, _types5.METRIC_TYPE.BEHAVIORAL, this.mobiusHost, clientRegionInfo.clientRegion, clientRegionInfo.countryCode, (_response$headers$tra = response === null || response === void 0 ? void 0 : (_response$headers2 = response.headers) === null || _response$headers2 === void 0 ? void 0 : _response$headers2.trackingid) !== null && _response$headers$tra !== void 0 ? _response$headers$tra : '');
              _context1.next = 6;
              break;
            case 3:
              _context1.prev = 3;
              _t4 = _context1["catch"](1);
              _Logger.default.error("Failed to get client region info: ".concat((0, _stringify.default)(_t4)), {
                method: _constants2.METHODS.GET_CLIENT_REGION_INFO,
                file: _constants2.CALLING_CLIENT_FILE
              });

              // eslint-disable-next-line no-await-in-loop
              _context1.next = 4;
              return (0, _Utils.handleCallingClientErrors)(_t4, function (clientError) {
                var _headers$trackingId, _headers2;
                _this3.metricManager.submitRegistrationMetric(_types5.METRIC_EVENT.REGISTRATION_ERROR, _types5.REG_ACTION.REGISTER, _types5.METRIC_TYPE.BEHAVIORAL, _constants2.GET_MOBIUS_SERVERS_UTIL, 'UNKNOWN', (_headers$trackingId = (_headers2 = _t4.headers) === null || _headers2 === void 0 ? void 0 : _headers2.trackingId) !== null && _headers$trackingId !== void 0 ? _headers$trackingId : '', undefined, clientError);
                _this3.emit(_types2.CALLING_CLIENT_EVENT_KEYS.ERROR, clientError);
              }, {
                method: _constants2.GET_MOBIUS_SERVERS_UTIL,
                file: _constants2.CALLING_CLIENT_FILE
              });
            case 4:
              abort = _context1.sent;
              regionInfo.clientRegion = '';
              regionInfo.countryCode = '';
              if (!abort) {
                _context1.next = 6;
                break;
              }
              _context1.next = 5;
              return (0, _Utils.uploadLogs)();
            case 5:
              return _context1.abrupt("return", regionInfo);
            case 6:
              return _context1.abrupt("return", regionInfo);
            case 7:
            case "end":
              return _context1.stop();
          }
        }, _callee0, this, [[1, 3]]);
      }));
      function getClientRegionInfo() {
        return _getClientRegionInfo.apply(this, arguments);
      }
      return getClientRegionInfo;
    }()
    /**
     * Local method for finding the mobius servers.
     */
    )
  }, {
    key: "getMobiusServers",
    value: (function () {
      var _getMobiusServers = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee1() {
        var _this$sdkConfig4,
          _this$sdkConfig4$disc,
          _this$sdkConfig5,
          _this$sdkConfig5$disc,
          _this4 = this;
        var useDefault, clientRegion, countryCode, _this$sdkConfig6, _this$sdkConfig6$disc, _this$sdkConfig7, _this$sdkConfig7$disc, _this$webex$internal$, regionInfo, _iterator2, _step2, _loop2, _ret, _t6;
        return _regenerator.default.wrap(function (_context11) {
          while (1) switch (_context11.prev = _context11.next) {
            case 0:
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.GET_MOBIUS_SERVERS
              });
              /* Following operations are performed in a synchronous way ->
                   1. Get RegionInfo
                  2. Get Mobius Server with that RegionInfo
                  3. Check whether Mobius server was found without any error
                  4. If there is error , we don't need to send registration
                  5. Otherwise send registration
                  */
              useDefault = false;
              if (!((_this$sdkConfig4 = this.sdkConfig) !== null && _this$sdkConfig4 !== void 0 && (_this$sdkConfig4$disc = _this$sdkConfig4.discovery) !== null && _this$sdkConfig4$disc !== void 0 && _this$sdkConfig4$disc.country && (_this$sdkConfig5 = this.sdkConfig) !== null && _this$sdkConfig5 !== void 0 && (_this$sdkConfig5$disc = _this$sdkConfig5.discovery) !== null && _this$sdkConfig5$disc !== void 0 && _this$sdkConfig5$disc.region)) {
                _context11.next = 1;
                break;
              }
              _Logger.default.log('Updating region and country from the SDK config', {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.GET_MOBIUS_SERVERS_UTIL
              });
              clientRegion = (_this$sdkConfig6 = this.sdkConfig) === null || _this$sdkConfig6 === void 0 ? void 0 : (_this$sdkConfig6$disc = _this$sdkConfig6.discovery) === null || _this$sdkConfig6$disc === void 0 ? void 0 : _this$sdkConfig6$disc.region;
              countryCode = (_this$sdkConfig7 = this.sdkConfig) === null || _this$sdkConfig7 === void 0 ? void 0 : (_this$sdkConfig7$disc = _this$sdkConfig7.discovery) === null || _this$sdkConfig7$disc === void 0 ? void 0 : _this$sdkConfig7$disc.country;
              this.mobiusHost = ((_this$webex$internal$ = this.webex.internal.services._serviceUrls) === null || _this$webex$internal$ === void 0 ? void 0 : _this$webex$internal$.mobius) || this.webex.internal.services.get(this.webex.internal.services._activeServices.mobius);
              _context11.next = 3;
              break;
            case 1:
              _Logger.default.log('Updating region and country through Region discovery', {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.GET_MOBIUS_SERVERS_UTIL
              });
              _context11.next = 2;
              return this.getClientRegionInfo();
            case 2:
              regionInfo = _context11.sent;
              clientRegion = regionInfo.clientRegion;
              countryCode = regionInfo.countryCode;
            case 3:
              if (!(clientRegion && countryCode)) {
                _context11.next = 12;
                break;
              }
              _Logger.default.log("Found Region: ".concat(clientRegion, " and country: ").concat(countryCode, ", going to fetch Mobius server"), {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.GET_MOBIUS_SERVERS_UTIL
              });
              _iterator2 = _createForOfIteratorHelper(this.mobiusClusters);
              _context11.prev = 4;
              _loop2 = /*#__PURE__*/_regenerator.default.mark(function _loop2() {
                var mobius, _response$headers3, _response$headers$tra2, _response$headers4, response, mobiusServers, mobiusUris, abort, _t5;
                return _regenerator.default.wrap(function (_context10) {
                  while (1) switch (_context10.prev = _context10.next) {
                    case 0:
                      mobius = _step2.value;
                      if (mobius.host) {
                        _this4.mobiusHost = "https://".concat(mobius.host).concat(_constants2.API_V1);
                      } else {
                        _this4.mobiusHost = mobius;
                      }
                      _context10.prev = 1;
                      _context10.next = 2;
                      return _this4.webex.request({
                        uri: "".concat(_this4.mobiusHost).concat(_constants2.URL_ENDPOINT, "?regionCode=").concat(clientRegion, "&countryCode=").concat(countryCode),
                        method: _types3.HTTP_METHODS.GET,
                        headers: (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _constants2.CISCO_DEVICE_URL, _this4.webex.internal.device.url), _constants2.SPARK_USER_AGENT, _constants2.CALLING_USER_AGENT),
                        service: _types3.ALLOWED_SERVICES.MOBIUS
                      });
                    case 2:
                      response = _context10.sent;
                      _Logger.default.log("Mobius Server found for the region. Response trackingId: ".concat(response === null || response === void 0 ? void 0 : (_response$headers3 = response.headers) === null || _response$headers3 === void 0 ? void 0 : _response$headers3.trackingid), {
                        file: _constants2.CALLING_CLIENT_FILE,
                        method: _constants2.GET_MOBIUS_SERVERS_UTIL
                      });
                      mobiusServers = response.body; // Metrics for mobius servers
                      _this4.metricManager.submitMobiusServersMetric(_types5.METRIC_EVENT.MOBIUS_DISCOVERY, _types5.MOBIUS_SERVER_ACTION.MOBIUS_SERVERS, _types5.METRIC_TYPE.BEHAVIORAL, mobiusServers, (_response$headers$tra2 = response === null || response === void 0 ? void 0 : (_response$headers4 = response.headers) === null || _response$headers4 === void 0 ? void 0 : _response$headers4.trackingid) !== null && _response$headers$tra2 !== void 0 ? _response$headers$tra2 : '');

                      /* update arrays of Mobius Uris. */
                      mobiusUris = (0, _Utils.filterMobiusUris)(mobiusServers, _this4.mobiusHost);
                      _this4.primaryMobiusUris = mobiusUris.primary;
                      _this4.backupMobiusUris = mobiusUris.backup;
                      _this4.primaryWssMobiusUris = mobiusUris.primaryWss;
                      _this4.backupWssMobiusUris = mobiusUris.backupWss;
                      _Logger.default.log("Final list of Mobius Servers, primary: ".concat(mobiusUris.primary, " and backup: ").concat(mobiusUris.backup), {
                        file: _constants2.CALLING_CLIENT_FILE,
                        method: _constants2.GET_MOBIUS_SERVERS_UTIL
                      });
                      return _context10.abrupt("return", 0);
                    case 3:
                      _context10.prev = 3;
                      _t5 = _context10["catch"](1);
                      _Logger.default.error("Failed to get Mobius servers: ".concat((0, _stringify.default)(_t5)), {
                        method: _constants2.METHODS.GET_MOBIUS_SERVERS,
                        file: _constants2.CALLING_CLIENT_FILE
                      });

                      // eslint-disable-next-line no-await-in-loop
                      _context10.next = 4;
                      return (0, _Utils.handleCallingClientErrors)(_t5, function (clientError) {
                        var _headers$trackingId2, _headers4;
                        _this4.metricManager.submitRegistrationMetric(_types5.METRIC_EVENT.REGISTRATION_ERROR, _types5.REG_ACTION.REGISTER, _types5.METRIC_TYPE.BEHAVIORAL, _constants2.GET_MOBIUS_SERVERS_UTIL, 'UNKNOWN', (_headers$trackingId2 = (_headers4 = _t5.headers) === null || _headers4 === void 0 ? void 0 : _headers4.trackingId) !== null && _headers$trackingId2 !== void 0 ? _headers$trackingId2 : '', undefined, clientError);
                        _this4.emit(_types2.CALLING_CLIENT_EVENT_KEYS.ERROR, clientError);
                      }, {
                        method: _constants2.GET_MOBIUS_SERVERS_UTIL,
                        file: _constants2.CALLING_CLIENT_FILE
                      });
                    case 4:
                      abort = _context10.sent;
                      if (!abort) {
                        _context10.next = 6;
                        break;
                      }
                      useDefault = true;
                      // eslint-disable-next-line no-await-in-loop
                      _context10.next = 5;
                      return (0, _Utils.uploadLogs)();
                    case 5:
                      return _context10.abrupt("return", 0);
                    case 6:
                    case "end":
                      return _context10.stop();
                  }
                }, _loop2, null, [[1, 3]]);
              });
              _iterator2.s();
            case 5:
              if ((_step2 = _iterator2.n()).done) {
                _context11.next = 8;
                break;
              }
              return _context11.delegateYield(_loop2(), "t0", 6);
            case 6:
              _ret = _context11.t0;
              if (!(_ret === 0)) {
                _context11.next = 7;
                break;
              }
              return _context11.abrupt("continue", 8);
            case 7:
              _context11.next = 5;
              break;
            case 8:
              _context11.next = 10;
              break;
            case 9:
              _context11.prev = 9;
              _t6 = _context11["catch"](4);
              _iterator2.e(_t6);
            case 10:
              _context11.prev = 10;
              _iterator2.f();
              return _context11.finish(10);
            case 11:
              _context11.next = 13;
              break;
            case 12:
              /* Setting this to true because region info is possibly undefined */
              useDefault = true;
            case 13:
              /* Use a default URL if Mobius discovery fails either because of region info failure
               * or because the discovered Mobius couldn't be reached
               */

              if (useDefault) {
                _Logger.default.warn("Couldn't resolve the region and country code. Defaulting to the catalog entries to discover mobius servers", {
                  file: _constants2.CALLING_CLIENT_FILE,
                  method: _constants2.GET_MOBIUS_SERVERS_UTIL
                });
                this.mobiusHost = "https://".concat(this.mobiusClusters[0].host).concat(_constants2.API_V1);
                this.primaryMobiusUris = ["".concat(this.mobiusHost).concat(_constants2.URL_ENDPOINT)];
              }
            case 14:
            case "end":
              return _context11.stop();
          }
        }, _callee1, this, [[4, 9, 10, 11]]);
      }));
      function getMobiusServers() {
        return _getMobiusServers.apply(this, arguments);
      }
      return getMobiusServers;
    }()
    /**
     * Connects to the Mobius WebSocket using WSS URIs discovered during Mobius server discovery.
     * Attempts primary WSS URIs first, then falls back to backup WSS URIs.
     * If all attempts fail, logs a warning and continues without a socket connection.
     */
    )
  }, {
    key: "connectToMobiusSocket",
    value: (function () {
      var _connectToMobiusSocket = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee10() {
        var loggerContext, _iterator3, _step3, wssUri, _iterator4, _step4, _wssUri, _t7, _t8, _t9, _t0;
        return _regenerator.default.wrap(function (_context12) {
          while (1) switch (_context12.prev = _context12.next) {
            case 0:
              loggerContext = {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.CONNECT_TO_MOBIUS_SOCKET
              };
              _Logger.default.info(_constants.METHOD_START_MESSAGE, loggerContext);
              if (!(!this.primaryWssMobiusUris.length && !this.backupWssMobiusUris.length)) {
                _context12.next = 1;
                break;
              }
              _Logger.default.warn('No WSS URIs available from Mobius discovery, skipping socket connection', loggerContext);
              return _context12.abrupt("return");
            case 1:
              if (!this.primaryWssMobiusUris.length) {
                _context12.next = 12;
                break;
              }
              _Logger.default.log("Attempting Mobius socket connection using primary WSS URIs (".concat(this.primaryWssMobiusUris.length, " available)"), loggerContext);
              _iterator3 = _createForOfIteratorHelper(this.primaryWssMobiusUris);
              _context12.prev = 2;
              _iterator3.s();
            case 3:
              if ((_step3 = _iterator3.n()).done) {
                _context12.next = 8;
                break;
              }
              wssUri = _step3.value;
              _context12.prev = 4;
              _Logger.default.log("Trying primary WSS URI: ".concat(wssUri), loggerContext);
              // eslint-disable-next-line no-await-in-loop
              _context12.next = 5;
              return this.apiRequest.connectToMobiusSocket(wssUri);
            case 5:
              _Logger.default.log("Successfully connected to Mobius socket on primary WSS URI: ".concat(wssUri), loggerContext);
              return _context12.abrupt("return");
            case 6:
              _context12.prev = 6;
              _t7 = _context12["catch"](4);
              _Logger.default.warn("Primary WSS URI connection failed for ".concat(wssUri, ": ").concat(_t7), loggerContext);
            case 7:
              _context12.next = 3;
              break;
            case 8:
              _context12.next = 10;
              break;
            case 9:
              _context12.prev = 9;
              _t8 = _context12["catch"](2);
              _iterator3.e(_t8);
            case 10:
              _context12.prev = 10;
              _iterator3.f();
              return _context12.finish(10);
            case 11:
              _Logger.default.warn('All primary WSS URI connection attempts failed', loggerContext);
              _context12.next = 13;
              break;
            case 12:
              _Logger.default.warn('No primary WSS URIs available, skipping to backup', loggerContext);
            case 13:
              if (!this.backupWssMobiusUris.length) {
                _context12.next = 24;
                break;
              }
              _Logger.default.log("Attempting Mobius socket connection using backup WSS URIs (".concat(this.backupWssMobiusUris.length, " available)"), loggerContext);
              _iterator4 = _createForOfIteratorHelper(this.backupWssMobiusUris);
              _context12.prev = 14;
              _iterator4.s();
            case 15:
              if ((_step4 = _iterator4.n()).done) {
                _context12.next = 20;
                break;
              }
              _wssUri = _step4.value;
              _context12.prev = 16;
              _Logger.default.log("Trying backup WSS URI: ".concat(_wssUri), loggerContext);
              // eslint-disable-next-line no-await-in-loop
              _context12.next = 17;
              return this.apiRequest.connectToMobiusSocket(_wssUri);
            case 17:
              _Logger.default.log("Successfully connected to Mobius socket on backup WSS URI: ".concat(_wssUri), loggerContext);
              return _context12.abrupt("return");
            case 18:
              _context12.prev = 18;
              _t9 = _context12["catch"](16);
              _Logger.default.warn("Backup WSS URI connection failed for ".concat(_wssUri, ": ").concat(_t9), loggerContext);
            case 19:
              _context12.next = 15;
              break;
            case 20:
              _context12.next = 22;
              break;
            case 21:
              _context12.prev = 21;
              _t0 = _context12["catch"](14);
              _iterator4.e(_t0);
            case 22:
              _context12.prev = 22;
              _iterator4.f();
              return _context12.finish(22);
            case 23:
              _Logger.default.warn('All backup WSS URI connection attempts failed', loggerContext);
              _context12.next = 25;
              break;
            case 24:
              _Logger.default.warn('No backup WSS URIs available', loggerContext);
            case 25:
              // Throwing an error is not required here. Connection will be attempted again during registration if no connection is established.
              // We might remove this connection attempt logic during optimization since we are anyway going to try to connect to Mobius during
              // registration and without registration the connection will be closed automatically by the mobius server.
              _Logger.default.warn('All Mobius socket connection attempts exhausted for both primary and backup, continuing without socket', loggerContext);
            case 26:
            case "end":
              return _context12.stop();
          }
        }, _callee10, this, [[2, 9, 10, 11], [4, 6], [14, 21, 22, 23], [16, 18]]);
      }));
      function connectToMobiusSocket() {
        return _connectToMobiusSocket.apply(this, arguments);
      }
      return connectToMobiusSocket;
    }())
  }, {
    key: "registerCallsClearedListener",
    value:
    /**
     * Registers a listener/handler for ALL_CALLS_CLEARED
     * event emitted by callManager when all the calls
     * present on sdk are cleaned up.
     */
    function registerCallsClearedListener() {
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.CALLING_CLIENT_FILE,
        method: _constants2.METHODS.REGISTER_CALLS_CLEARED_LISTENER
      });
      this.callManager.on(_types2.CALLING_CLIENT_EVENT_KEYS.ALL_CALLS_CLEARED, this.callsClearedHandler);
    }
  }, {
    key: "getLoggingLevel",
    value:
    /**
     * To get the current log Level.
     * @ignore
     */
    function getLoggingLevel() {
      return _Logger.default.getLogLevel();
    }

    /**
     *  To return the `sdkConnector` instance that was used during sdk initialisation.
     * @ignore
     */
  }, {
    key: "getSDKConnector",
    value: function getSDKConnector() {
      return this.sdkConnector;
    }
  }, {
    key: "registerSessionsListener",
    value: function registerSessionsListener() {
      var _this5 = this;
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.CALLING_CLIENT_FILE,
        method: _constants2.METHODS.REGISTER_SESSIONS_LISTENER
      });
      this.sdkConnector.registerListener(_types2.MOBIUS_EVENT_KEYS.CALL_SESSION_EVENT_INCLUSIVE, /*#__PURE__*/function () {
        var _ref7 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee11(event) {
          var sessionArr, i;
          return _regenerator.default.wrap(function (_context13) {
            while (1) switch (_context13.prev = _context13.next) {
              case 0:
                if (!(event && event.data.userSessions.userSessions)) {
                  _context13.next = 2;
                  break;
                }
                sessionArr = event === null || event === void 0 ? void 0 : event.data.userSessions.userSessions;
                if (!(sessionArr.length === 1)) {
                  _context13.next = 1;
                  break;
                }
                if (!(sessionArr[0].sessionType !== _types2.SessionType.WEBEX_CALLING)) {
                  _context13.next = 1;
                  break;
                }
                return _context13.abrupt("return");
              case 1:
                for (i = 0; i < sessionArr.length; i += 1) {
                  if (sessionArr[i].sessionType !== _types2.SessionType.WEBEX_CALLING) {
                    sessionArr.splice(i, 1);
                  }
                }
                _this5.emit(_types2.CALLING_CLIENT_EVENT_KEYS.USER_SESSION_INFO, event);
              case 2:
              case "end":
                return _context13.stop();
            }
          }, _callee11);
        }));
        return function (_x2) {
          return _ref7.apply(this, arguments);
        };
      }());
    }

    /**
     * Creates line object inside calling client per user
     * NOTE: currently multiple lines are not supported
     */
  }, {
    key: "createLine",
    value: (function () {
      var _createLine = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee12() {
        var _this$sdkConfig8;
        var line;
        return _regenerator.default.wrap(function (_context14) {
          while (1) switch (_context14.prev = _context14.next) {
            case 0:
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.CREATE_LINE
              });
              line = new _line.default(this.webex.internal.device.userId, this.webex.internal.device.url, this.mutex, this.apiRequest.isSocketEnabled() ? (0, _Utils.normalizeMobiusUris)(this.primaryWssMobiusUris) : this.primaryMobiusUris, this.apiRequest.isSocketEnabled() ? (0, _Utils.normalizeMobiusUris)(this.backupWssMobiusUris) : this.backupMobiusUris, this.getLoggingLevel(), this.serviceData, (_this$sdkConfig8 = this.sdkConfig) === null || _this$sdkConfig8 === void 0 ? void 0 : _this$sdkConfig8.jwe);
              this.lineDict[line.lineId] = line;
            case 1:
            case "end":
              return _context14.stop();
          }
        }, _callee12, this);
      }));
      function createLine() {
        return _createLine.apply(this, arguments);
      }
      return createLine;
    }()
    /**
     * Retrieves details of all the Line objects belonging to a User
     * NOTE: currently multiple lines are not supported
     */
    )
  }, {
    key: "getLines",
    value: function getLines() {
      return this.lineDict;
    }

    /**
     * Fetches the list of devices for a given user from Mobius.
     */
  }, {
    key: "getDevices",
    value: (function () {
      var _getDevices = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee13(userId) {
        var userid, mobiusUrls, finalError, _iterator5, _step5, mobiusUrl, normalizedMobiusUrl, uri, _body$devices, response, body, _t1, _t10;
        return _regenerator.default.wrap(function (_context15) {
          while (1) switch (_context15.prev = _context15.next) {
            case 0:
              userid = userId || this.webex.internal.device.userId;
              if (userid) {
                _context15.next = 1;
                break;
              }
              throw new Error('userId is required to fetch devices');
            case 1:
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.GET_DEVICES
              });
              mobiusUrls = [].concat((0, _toConsumableArray2.default)(this.primaryMobiusUris), (0, _toConsumableArray2.default)(this.backupMobiusUris));
              if (!(mobiusUrls.length === 0)) {
                _context15.next = 2;
                break;
              }
              throw new Error('Mobius URLs are not available');
            case 2:
              _iterator5 = _createForOfIteratorHelper(mobiusUrls);
              _context15.prev = 3;
              _iterator5.s();
            case 4:
              if ((_step5 = _iterator5.n()).done) {
                _context15.next = 10;
                break;
              }
              mobiusUrl = _step5.value;
              normalizedMobiusUrl = mobiusUrl.replace(/\/+$/, '/');
              uri = "".concat(normalizedMobiusUrl).concat(_constants2.DEVICES_ENDPOINT_RESOURCE, "?userid=").concat(encodeURIComponent(userid));
              _context15.prev = 5;
              _context15.next = 6;
              return this.webex.request({
                uri: uri,
                method: _types3.HTTP_METHODS.GET,
                service: _types3.ALLOWED_SERVICES.MOBIUS,
                headers: (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _constants2.CISCO_DEVICE_URL, this.webex.internal.device.url), _constants2.SPARK_USER_AGENT, _constants2.CALLING_USER_AGENT)
              });
            case 6:
              response = _context15.sent;
              if (!(response.statusCode !== 200)) {
                _context15.next = 7;
                break;
              }
              throw new Error("API call failed with ".concat(response.statusCode));
            case 7:
              body = response.body; // Hydrate registration deviceInfo for deregister/restore flows
              (0, _values.default)(this.lineDict)[0].registration.setDeviceInfo(body);
              (0, _values.default)(this.lineDict)[0].registration.setActiveMobiusUrl(normalizedMobiusUrl);
              return _context15.abrupt("return", (_body$devices = body.devices) !== null && _body$devices !== void 0 ? _body$devices : []);
            case 8:
              _context15.prev = 8;
              _t1 = _context15["catch"](5);
              finalError = _t1;
            case 9:
              _context15.next = 4;
              break;
            case 10:
              _context15.next = 12;
              break;
            case 11:
              _context15.prev = 11;
              _t10 = _context15["catch"](3);
              _iterator5.e(_t10);
            case 12:
              _context15.prev = 12;
              _iterator5.f();
              return _context15.finish(12);
            case 13:
              _Logger.default.error("Failed to fetch devices for userId ".concat(userId, ": ").concat((0, _stringify.default)(finalError)), {
                file: _constants2.CALLING_CLIENT_FILE,
                method: _constants2.METHODS.GET_DEVICES
              });
              throw finalError;
            case 14:
            case "end":
              return _context15.stop();
          }
        }, _callee13, this, [[3, 11, 12, 13], [5, 8]]);
      }));
      function getDevices(_x3) {
        return _getDevices.apply(this, arguments);
      }
      return getDevices;
    }()
    /**
     * Retrieves call objects for all the active calls present in the client
     */
    )
  }, {
    key: "getActiveCalls",
    value: function getActiveCalls() {
      var activeCalls = {};
      var calls = this.callManager.getActiveCalls();
      (0, _keys.default)(calls).forEach(function (correlationId) {
        var call = calls[correlationId];
        if (!activeCalls[call.lineId]) {
          activeCalls[call.lineId] = [];
        }
        activeCalls[call.lineId].push(call);
      });
      return activeCalls;
    }

    /**
     * Retrieves call object for the connected call in the client
     */
  }, {
    key: "getConnectedCall",
    value: function getConnectedCall() {
      var connectCall;
      var calls = this.callManager.getActiveCalls();
      (0, _keys.default)(calls).forEach(function (correlationId) {
        if (calls[correlationId].isConnected() && !calls[correlationId].isHeld()) {
          connectCall = calls[correlationId];
        }
      });
      return connectCall;
    }

    /**
     * Uploads logs to help troubleshoot SDK issues.
     *
     * This method collects the current SDK logs including network requests, WebSocket
     * messages, and client-side events, then securely submits them to Webex's diagnostics
     * service. The returned tracking ID, feedbackID can be provided to Webex support for faster
     * issue resolution.
     * @returns Promise<UploadLogsResponse>
     * @throws Error
     */
  }, {
    key: "uploadLogs",
    value: (function () {
      var _uploadLogs2 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee14() {
        var result;
        return _regenerator.default.wrap(function (_context16) {
          while (1) switch (_context16.prev = _context16.next) {
            case 0:
              _context16.next = 1;
              return (0, _Utils.uploadLogs)({}, true);
            case 1:
              result = _context16.sent;
              if (result) {
                _context16.next = 2;
                break;
              }
              throw new Error('Failed to upload logs: No response received.');
            case 2:
              return _context16.abrupt("return", result);
            case 3:
            case "end":
              return _context16.stop();
          }
        }, _callee14);
      }));
      function uploadLogs() {
        return _uploadLogs2.apply(this, arguments);
      }
      return uploadLogs;
    }())
  }]);
}(_impl.Eventing);
/**
 * Create the `CallingClient` instance using the `webex` object and callingSdk `config`
 * @param webex - A webex instance.
 * @param config - Config to start the CallingClient with.
 */
var createClient = exports.createClient = /*#__PURE__*/function () {
  var _ref8 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee15(webex, config) {
    var callingClientInstance;
    return _regenerator.default.wrap(function (_context17) {
      while (1) switch (_context17.prev = _context17.next) {
        case 0:
          callingClientInstance = new CallingClient(webex, config);
          _context17.next = 1;
          return callingClientInstance.init();
        case 1:
          return _context17.abrupt("return", callingClientInstance);
        case 2:
        case "end":
          return _context17.stop();
      }
    }, _callee15);
  }));
  return function createClient(_x4, _x5) {
    return _ref8.apply(this, arguments);
  };
}();
//# sourceMappingURL=CallingClient.js.map
