"use strict";

var _typeof = require("@babel/runtime-corejs2/helpers/typeof");
var _Object$keys2 = require("@babel/runtime-corejs2/core-js/object/keys");
var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs2/core-js/object/get-own-property-symbols");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptors");
var _Object$defineProperties = require("@babel/runtime-corejs2/core-js/object/define-properties");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
var _values = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/values"));
var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));
var _asyncMutex = require("async-mutex");
var Media = _interopRequireWildcard(require("@webex/internal-media-core"));
var _types = require("../Logger/types");
var _testUtil = require("../common/testUtil");
var _types2 = require("../common/types");
var _types3 = require("../Events/types");
var _Logger = _interopRequireDefault(require("../Logger"));
var _CallingClient = require("./CallingClient");
var _Utils = _interopRequireWildcard(require("../common/Utils"));
var utils = _Utils;
var _callManager = require("./calling/callManager");
var _constants = require("./constants");
var _callRecordFixtures = require("./callRecordFixtures");
var _callingClientFixtures = require("./callingClientFixtures");
var _line = _interopRequireDefault(require("./line"));
var _registerFixtures = require("./registration/registerFixtures");
var _constants2 = require("../common/constants");
var _types4 = require("../Metrics/types");
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 _t4 in e) "default" !== _t4 && {}.hasOwnProperty.call(e, _t4) && ((i = (o = _Object$defineProperty) && _Object$getOwnPropertyDescriptor(e, _t4)) && (i.get || i.set) ? o(f, _t4, i) : f[_t4] = e[_t4]); return f; })(e, t); }
function ownKeys(e, r) { var t = _Object$keys2(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; } /* eslint-disable dot-notation */
jest.mock('../mobius-socket', function () {
  return {
    getMobiusSocketInstance: jest.fn().mockReturnValue({
      sendWssRequest: jest.fn(),
      connect: jest.fn(),
      on: jest.fn(),
      off: jest.fn()
    })
  };
});
global.crypto = {
  randomUUID: function randomUUID() {
    return '12345678-1234-5678-1234-567812345678';
  }
};
jest.spyOn(utils, 'uploadLogs').mockResolvedValue(undefined);
describe('CallingClient Tests', function () {
  // Common initializers

  var handleErrorSpy = jest.spyOn(utils, 'handleCallingClientErrors');
  var setLoggerSpy = jest.spyOn(Media, 'setLogger');
  var webex = (0, _testUtil.getTestUtilsWebex)();
  webex.internal.services['_hostCatalog'] = _callingClientFixtures.mockCatalogUS;
  webex.internal.services.getMobiusClusters = jest.fn().mockReturnValue(_callingClientFixtures.mockUSServiceHosts);
  var defaultServiceIndicator = _types2.ServiceIndicator.CALLING;
  var callManager = (0, _callManager.getCallManager)(webex, defaultServiceIndicator);
  var infoSpy = jest.spyOn(_Logger.default, 'info');
  var logSpy = jest.spyOn(_Logger.default, 'log');
  var warnSpy = jest.spyOn(_Logger.default, 'warn');
  var originalProcessNextTick = process.nextTick;
  function flushPromises() {
    return new _promise.default(function (resolve) {
      originalProcessNextTick(resolve);
    });
  }
  beforeEach(function () {
    _request.APIRequest.resetInstance();
    _request.APIRequest.getInstance({
      webex: webex
    });
  });
  describe('CallingClient pick Mobius cluster using Service Host Tests', function () {
    afterAll(function () {
      callManager.removeAllListeners();
      webex.internal.services['_serviceUrls']['mobius'] = 'https://mobius.aintgen-a-1.int.infra.webex.com/api/v1';
      webex.internal.services['_hostCatalog'] = _callingClientFixtures.mockCatalogUS;
    });
    it('should use default mobius service host when Service URL is invalid', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
      var callingClient;
      return _regenerator.default.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            webex.internal.services._hostCatalog = _callingClientFixtures.mockCatalogUS;
            webex.internal.services._serviceUrls.mobius = 'invalid-url';
            _context.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context.sent;
            expect(setLoggerSpy).toHaveBeenCalledTimes(1);
            expect(callingClient['mobiusClusters']).toStrictEqual(_callingClientFixtures.mockUSServiceHosts);
          case 2:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    it('should set mobiusServiceHost correctly when URL is valid', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
      var callingClient;
      return _regenerator.default.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            webex.internal.services._hostCatalog = _callingClientFixtures.mockCatalogEU;
            webex.internal.services.getMobiusClusters = jest.fn().mockReturnValue(_callingClientFixtures.mockEUServiceHosts);
            webex.internal.services['_serviceUrls']['mobius'] = 'https://mobius-eu-central-1.prod.infra.webex.com/api/v1';
            _context2.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context2.sent;
            expect(callingClient['mobiusHost']).toBe('https://mobius-eu-central-1.prod.infra.webex.com/api/v1');
            expect(callingClient['mobiusClusters']).toStrictEqual(_callingClientFixtures.mockEUServiceHosts);
          case 2:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    })));
  });
  describe('ServiceData tests', function () {
    var callingClient;
    afterEach(function () {
      callManager.removeAllListeners();
      callingClient = undefined;
    });

    /**
     * No input sdk config to callingClient, it should default to service type
     * calling and empty domain value.
     */
    it('Verify valid calling serviceData with no input sdk config', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4() {
      return _regenerator.default.wrap(function (_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            expect(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
              return _regenerator.default.wrap(function (_context3) {
                while (1) switch (_context3.prev = _context3.next) {
                  case 0:
                    _context3.next = 1;
                    return (0, _CallingClient.createClient)(webex);
                  case 1:
                    callingClient = _context3.sent;
                    expect(callingClient).toBeTruthy();
                  case 2:
                  case "end":
                    return _context3.stop();
                }
              }, _callee3);
            }))).not.toThrow(Error);
          case 1:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    })));

    /**
     * Input sdk config to callingClient with serviceData carrying empty string for
     * both indicator and domain in it.
     *
     * It should default to service type calling and empty domain value.
     *
     */
    it('Verify invalid empty service indicator, empty domain', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee6() {
      var serviceDataObj;
      return _regenerator.default.wrap(function (_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            /* eslint-disable @typescript-eslint/no-explicit-any */
            serviceDataObj = {
              indicator: '',
              domain: ''
            };
            expect(/*#__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:
                    _context5.next = 1;
                    return (0, _CallingClient.createClient)(webex, {
                      serviceData: serviceDataObj
                    });
                  case 1:
                    callingClient = _context5.sent;
                    expect(callingClient).toBeTruthy();
                  case 2:
                  case "end":
                    return _context5.stop();
                }
              }, _callee5);
            }))).not.toThrow(Error);
          case 1:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    })));

    /**
     * Input sdk config to callingClient with serviceData carrying invalid value for indicator
     * and valid domain type string for domain field in it.
     *
     * It should throw error and abort execution as indicator value is invalid.
     *
     * INDICATOR value MUST MATCH with one of the values in ServiceIndicator enum.
     */
    it('Verify invalid service indicator, valid domain', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee7() {
      var serviceDataObj, _t;
      return _regenerator.default.wrap(function (_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            /* eslint-disable @typescript-eslint/no-explicit-any */
            serviceDataObj = {
              indicator: 'test',
              domain: 'test.example.com'
            };
            _context7.prev = 1;
            _context7.next = 2;
            return (0, _CallingClient.createClient)(webex, {
              serviceData: serviceDataObj
            });
          case 2:
            callingClient = _context7.sent;
            _context7.next = 4;
            break;
          case 3:
            _context7.prev = 3;
            _t = _context7["catch"](1);
            expect(_t.message).toEqual('Invalid service indicator, Allowed values are: calling, contactcenter and guestcalling');
          case 4:
            expect.assertions(1);
          case 5:
          case "end":
            return _context7.stop();
        }
      }, _callee7, null, [[1, 3]]);
    })));

    /**
     * Input sdk config to callingClient with serviceData carrying valid value for indicator
     * 'calling', but an invalid domain type string for domain field in it.
     *
     * It should throw error and abort execution as domain value is invalid.
     *
     * DOMAIN field for service type calling is allowed to be empty but if it carries a non-empty
     * string then it must be of valid domain type.
     */
    it('CALLING: verify invalid service domain', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee8() {
      var serviceDataObj, _t2;
      return _regenerator.default.wrap(function (_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            serviceDataObj = {
              indicator: _types2.ServiceIndicator.CALLING,
              domain: 'test'
            };
            _context8.prev = 1;
            _context8.next = 2;
            return (0, _CallingClient.createClient)(webex, {
              serviceData: serviceDataObj
            });
          case 2:
            callingClient = _context8.sent;
            _context8.next = 4;
            break;
          case 3:
            _context8.prev = 3;
            _t2 = _context8["catch"](1);
            expect(_t2.message).toEqual('Invalid service domain.');
          case 4:
            expect.assertions(1);
          case 5:
          case "end":
            return _context8.stop();
        }
      }, _callee8, null, [[1, 3]]);
    })));

    /**
     * Input sdk config to callingClient with serviceData carrying valid value for indicator
     * 'calling', and an empty string for domain field in it.
     *
     * Execution should proceed properly and createRegistration should be called with same serviceData.
     *
     * DOMAIN field for service type 'calling' is allowed to be empty.
     */
    it('CALLING: verify valid empty service domain', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee0() {
      var serviceDataObj;
      return _regenerator.default.wrap(function (_context0) {
        while (1) switch (_context0.prev = _context0.next) {
          case 0:
            serviceDataObj = {
              indicator: _types2.ServiceIndicator.CALLING,
              domain: ''
            };
            expect(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee9() {
              return _regenerator.default.wrap(function (_context9) {
                while (1) switch (_context9.prev = _context9.next) {
                  case 0:
                    _context9.next = 1;
                    return (0, _CallingClient.createClient)(webex, {
                      serviceData: serviceDataObj
                    });
                  case 1:
                    callingClient = _context9.sent;
                    expect(callingClient).toBeTruthy();
                  case 2:
                  case "end":
                    return _context9.stop();
                }
              }, _callee9);
            }))).not.toThrow(Error);
          case 1:
          case "end":
            return _context0.stop();
        }
      }, _callee0);
    })));
    it('ContactCenter: uses config domain and does not fetch RTMS domain from catalog', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee1() {
      var serviceDataObj;
      return _regenerator.default.wrap(function (_context1) {
        while (1) switch (_context1.prev = _context1.next) {
          case 0:
            serviceDataObj = {
              indicator: _types2.ServiceIndicator.CONTACT_CENTER,
              domain: 'test.example.com'
            };
            webex.internal.services.get = jest.fn();
            _context1.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              serviceData: serviceDataObj
            });
          case 1:
            callingClient = _context1.sent;
            expect(callingClient).toBeTruthy();
            expect(webex.internal.services.get).not.toHaveBeenCalled();
          case 2:
          case "end":
            return _context1.stop();
        }
      }, _callee1);
    })));

    /**
     * Input sdk config to callingClient with serviceData carrying valid value for indicator
     * 'contactcenter' , and a valid domain type string for domain field in it.
     */
    it('ContactCenter: fetches RTMS domain from catalog when config domain is empty', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee10() {
      var serviceDataObj;
      return _regenerator.default.wrap(function (_context10) {
        while (1) switch (_context10.prev = _context10.next) {
          case 0:
            serviceDataObj = {
              indicator: _types2.ServiceIndicator.CONTACT_CENTER,
              domain: ''
            };
            webex.internal.services.get = jest.fn().mockReturnValue('https://cc-rtms.example.com/calling/web/rtms');
            _context10.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              serviceData: serviceDataObj
            });
          case 1:
            callingClient = _context10.sent;
            expect(callingClient).toBeTruthy();
            expect(webex.internal.services.get).toHaveBeenCalledWith('wcc-calling-rtms-domain');
          case 2:
          case "end":
            return _context10.stop();
        }
      }, _callee10);
    })));
    it('ContactCenter: init fails when config domain is empty and catalog fetch fails', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee11() {
      var serviceDataObj, createLineSpy;
      return _regenerator.default.wrap(function (_context11) {
        while (1) switch (_context11.prev = _context11.next) {
          case 0:
            serviceDataObj = {
              indicator: _types2.ServiceIndicator.CONTACT_CENTER,
              domain: ''
            };
            createLineSpy = jest.spyOn(_CallingClient.CallingClient.prototype, 'createLine');
            webex.internal.services.get = jest.fn(function () {
              throw new Error('catalog unavailable');
            });
            _context11.next = 1;
            return expect((0, _CallingClient.createClient)(webex, {
              serviceData: serviceDataObj
            })).rejects.toThrow('Invalid service domain.');
          case 1:
            expect(createLineSpy).not.toHaveBeenCalled();
            createLineSpy.mockRestore();
          case 2:
          case "end":
            return _context11.stop();
        }
      }, _callee11);
    })));
    it('Get current log level', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee12() {
      return _regenerator.default.wrap(function (_context12) {
        while (1) switch (_context12.prev = _context12.next) {
          case 0:
            _context12.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context12.sent;
            expect(callingClient).toBeTruthy();
            expect(callingClient.getLoggingLevel).toBeTruthy();
            expect(callingClient.getLoggingLevel()).toEqual(_types.LOGGER.INFO);
          case 2:
          case "end":
            return _context12.stop();
        }
      }, _callee12);
    })));
  });
  describe('Mobius Server discovery tests', function () {
    var callingClient;
    afterEach(function () {
      jest.clearAllTimers();
      jest.clearAllMocks();
      callingClient.removeAllListeners();
      callManager.removeAllListeners();
      callingClient = undefined;
      jest.useRealTimers();
    });
    it('verify successful mobius server url discovery', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee13() {
      return _regenerator.default.wrap(function (_context13) {
        while (1) switch (_context13.prev = _context13.next) {
          case 0:
            webex.request.mockResolvedValueOnce(_callingClientFixtures.regionPayload).mockResolvedValueOnce(_callingClientFixtures.discoveryPayload);
            _context13.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context13.sent;
            expect(webex.request).toBeCalledTimes(2);
            expect(callingClient.primaryMobiusUris).toEqual([_callingClientFixtures.primaryUrl]);
            expect(handleErrorSpy).not.toBeCalled();
            expect(webex.request).nthCalledWith(1, {
              method: 'GET',
              uri: "".concat(_constants.DISCOVERY_URL),
              addAuthHeader: false,
              headers: (0, _defineProperty2.default)({}, _constants.SPARK_USER_AGENT, null)
            });
            expect(webex.request).nthCalledWith(2, _objectSpread(_objectSpread({
              method: 'GET'
            }, (0, _testUtil.getMockRequestTemplate)()), {}, {
              uri: "".concat(callingClient['mobiusHost']).concat(_constants.URL_ENDPOINT, "?regionCode=").concat(_callingClientFixtures.regionBody.clientRegion, "&countryCode=").concat(_callingClientFixtures.regionBody.countryCode)
            }));
          case 2:
          case "end":
            return _context13.stop();
        }
      }, _callee13);
    })));
    it('when region discovery succeeds but region based mobius url discovery fails with final error', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee14() {
      var failurePayload;
      return _regenerator.default.wrap(function (_context14) {
        while (1) switch (_context14.prev = _context14.next) {
          case 0:
            failurePayload = {
              statusCode: 401
            };
            webex.request.mockResolvedValueOnce(_callingClientFixtures.regionPayload).mockRejectedValueOnce(failurePayload);
            _context14.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context14.sent;
            expect(handleErrorSpy).toBeCalledWith(failurePayload, expect.anything(), {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'getMobiusServers'
            });
            expect(webex.request).toBeCalledTimes(2);
            expect(callingClient.primaryMobiusUris).toEqual(["".concat(callingClient['mobiusHost']).concat(_constants.URL_ENDPOINT)]);
            expect(webex.request).nthCalledWith(1, {
              method: 'GET',
              uri: "".concat(_constants.DISCOVERY_URL),
              addAuthHeader: false,
              headers: (0, _defineProperty2.default)({}, _constants.SPARK_USER_AGENT, null)
            });
            expect(warnSpy).toBeCalledWith("Couldn't resolve the region and country code. Defaulting to the catalog entries to discover mobius servers", expect.objectContaining({
              file: _constants.CALLING_CLIENT_FILE,
              method: 'getMobiusServers'
            }));
          case 2:
          case "end":
            return _context14.stop();
        }
      }, _callee14);
    })));
    it('Verify successful mobius server url discovery after initializing callingClient through a config', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee15() {
      return _regenerator.default.wrap(function (_context15) {
        while (1) switch (_context15.prev = _context15.next) {
          case 0:
            infoSpy.mockReset();
            webex.request.mockResolvedValueOnce(_callingClientFixtures.discoveryPayload);
            _context15.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              discovery: {
                region: 'AP-SOUTHEAST',
                country: 'IN'
              },
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context15.sent;
            expect(callingClient.primaryMobiusUris).toEqual([_callingClientFixtures.primaryUrl]);
            expect(infoSpy).toHaveBeenCalledWith(_constants2.METHOD_START_MESSAGE, {
              file: 'CallingClient',
              method: 'getMobiusServers'
            });
            expect(webex.request).toBeCalledOnceWith(_objectSpread(_objectSpread({}, (0, _testUtil.getMockRequestTemplate)()), {}, {
              uri: "".concat(callingClient['mobiusHost']).concat(_constants.URL_ENDPOINT, "?regionCode=").concat(_callingClientFixtures.regionBody.clientRegion, "&countryCode=").concat(_callingClientFixtures.regionBody.countryCode),
              method: 'GET'
            }));
            expect(handleErrorSpy).not.toHaveBeenCalled();
          case 2:
          case "end":
            return _context15.stop();
        }
      }, _callee15);
    })));
  });
  describe('Testing each cluster present withing host catalog', function () {
    var mobiusCluster = ['mobius-eu-central-1.prod.infra.webex.com', 'mobius-us-east-1.int.infra.webex.com', 'mobius-eu-central-1.int.infra.webex.com'];
    var checkCluster = /*#__PURE__*/function () {
      var _ref16 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee16(mockServiceHosts, mockCatalog) {
        var callingClient;
        return _regenerator.default.wrap(function (_context16) {
          while (1) switch (_context16.prev = _context16.next) {
            case 0:
              webex.internal.services._hostCatalog = mockCatalog;
              webex.internal.services.getMobiusClusters = jest.fn().mockReturnValue(mockServiceHosts);
              _context16.next = 1;
              return (0, _CallingClient.createClient)(webex, {
                logger: {
                  level: _types.LOGGER.INFO
                }
              });
            case 1:
              callingClient = _context16.sent;
              expect(callingClient['mobiusClusters']).toStrictEqual(mockServiceHosts);
            case 2:
            case "end":
              return _context16.stop();
          }
        }, _callee16);
      }));
      return function checkCluster(_x, _x2) {
        return _ref16.apply(this, arguments);
      };
    }();
    it.each(mobiusCluster)('%s', /*#__PURE__*/function () {
      var _ref17 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee17(clusterName) {
        var _t3;
        return _regenerator.default.wrap(function (_context17) {
          while (1) switch (_context17.prev = _context17.next) {
            case 0:
              _t3 = clusterName;
              _context17.next = _t3 === 'mobius-eu-central-1.prod.infra.webex.com' ? 1 : _t3 === 'mobius-us-east-1.int.infra.webex.com' ? 2 : _t3 === 'mobius-eu-central-1.int.infra.webex.com' ? 3 : 4;
              break;
            case 1:
              checkCluster(_callingClientFixtures.mockEUServiceHosts, _callingClientFixtures.mockCatalogEU);
              return _context17.abrupt("continue", 5);
            case 2:
              checkCluster(_callingClientFixtures.mockIntServiceHosts, _callingClientFixtures.mockCatalogUSInt);
              return _context17.abrupt("continue", 5);
            case 3:
              checkCluster(_callingClientFixtures.mockEUIntServiceHosts, _callingClientFixtures.mockCatalogEUInt);
              return _context17.abrupt("continue", 5);
            case 4:
              return _context17.abrupt("continue", 5);
            case 5:
            case "end":
              return _context17.stop();
          }
        }, _callee17);
      }));
      return function (_x3) {
        return _ref17.apply(this, arguments);
      };
    }());
  });
  describe('Line creation tests', function () {
    var callingClient;
    var line;
    beforeEach(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee18() {
      return _regenerator.default.wrap(function (_context18) {
        while (1) switch (_context18.prev = _context18.next) {
          case 0:
            _context18.next = 1;
            return (0, _CallingClient.createClient)(webex);
          case 1:
            callingClient = _context18.sent;
            line = (0, _values.default)(callingClient.lineDict)[0];
          case 2:
          case "end":
            return _context18.stop();
        }
      }, _callee18);
    })));
    afterEach(function () {
      jest.clearAllTimers();
      jest.clearAllMocks();
      callingClient.removeAllListeners();
      callManager.removeAllListeners();
      callingClient = undefined;
      jest.useRealTimers();
    });
    it('verify line dict successfully created', function () {
      expect(callingClient.lineDict).toBeTruthy();
      expect(line).toBeTruthy();
      expect((0, _keys.default)(callingClient.lineDict).length).toEqual(1);
    });
    it('verify getLines response', function () {
      expect(callingClient.getLines).toBeTruthy();
      expect(callingClient.getLines()).toEqual(callingClient.lineDict);
    });
  });
  describe('Connectivity and Mercury event handlers', function () {
    var callingClient;
    var line;
    var reg;
    var windowEventSpy;
    var deRegSpy;
    var restoreSpy;
    var restartRegisterSpy;
    var registerSpy;
    var metricSpy;
    beforeEach(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee19() {
      return _regenerator.default.wrap(function (_context19) {
        while (1) switch (_context19.prev = _context19.next) {
          case 0:
            jest.useFakeTimers();
            webex.request.mockResolvedValueOnce(_callingClientFixtures.regionPayload).mockResolvedValueOnce(_callingClientFixtures.discoveryPayload).mockResolvedValueOnce(_callingClientFixtures.registrationPayload);
            windowEventSpy = jest.spyOn(window, 'addEventListener');
            _context19.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context19.sent;
            line = (0, _values.default)(callingClient.lineDict)[0];
            reg = line.registration;
            _context19.next = 2;
            return line.register();
          case 2:
            deRegSpy = jest.spyOn(reg, 'deregister');
            restoreSpy = jest.spyOn(reg, 'restorePreviousRegistration');
            restartRegisterSpy = jest.spyOn(reg, 'restartRegistration');
            registerSpy = jest.spyOn(reg, 'attemptRegistrationWithServers');
            metricSpy = jest.spyOn(callingClient['metricManager'], 'submitConnectionMetrics');
          case 3:
          case "end":
            return _context19.stop();
        }
      }, _callee19);
    })));
    afterEach(function () {
      jest.clearAllTimers();
      jest.clearAllMocks();
      callingClient.removeAllListeners();
      callingClient['callManager'].callCollection = {};
      callManager.removeAllListeners();
      callingClient = undefined;
      jest.useRealTimers();
    });
    it('window offline handler sets networkDown and clears keepalive when network is unreachable', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee20() {
      var g, clearKeepaliveSpy, offlineCb;
      return _regenerator.default.wrap(function (_context20) {
        while (1) switch (_context20.prev = _context20.next) {
          case 0:
            g = global;
            g.fetch = jest.fn().mockRejectedValueOnce(new Error('network fail'));
            clearKeepaliveSpy = jest.spyOn(reg, 'clearKeepaliveTimer');
            offlineCb = windowEventSpy.mock.calls[1][1];
            _context20.next = 1;
            return offlineCb();
          case 1:
            expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Network connectivity probe failed'), {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'pingExternal'
            });
            expect(callingClient['isNetworkDown']).toBe(true);
            expect(clearKeepaliveSpy).toHaveBeenCalled();
          case 2:
          case "end":
            return _context20.stop();
        }
      }, _callee20);
    })));
    it('window offline handler does not clear keepalive when network is reachable', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee21() {
      var g, clearKeepaliveSpy, offlineCb;
      return _regenerator.default.wrap(function (_context21) {
        while (1) switch (_context21.prev = _context21.next) {
          case 0:
            g = global;
            g.fetch = jest.fn().mockResolvedValueOnce({});
            clearKeepaliveSpy = jest.spyOn(reg, 'clearKeepaliveTimer');
            offlineCb = windowEventSpy.mock.calls[1][1];
            _context21.next = 1;
            return offlineCb();
          case 1:
            expect(g.fetch).toHaveBeenCalledWith('https://www.google.com/generate_204', expect.any(Object));
            expect(callingClient['isNetworkDown']).toBe(false);
            expect(clearKeepaliveSpy).not.toHaveBeenCalled();
          case 2:
          case "end":
            return _context21.stop();
        }
      }, _callee21);
    })));
    it('window online handler sets networkUpTimestamp and logs', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee22() {
      var onlineCb;
      return _regenerator.default.wrap(function (_context22) {
        while (1) switch (_context22.prev = _context22.next) {
          case 0:
            onlineCb = windowEventSpy.mock.calls[0][1];
            _context22.next = 1;
            return onlineCb();
          case 1:
            expect(callingClient['networkUpTimestamp']).toEqual(expect.any(String));
            expect(infoSpy).toHaveBeenCalledWith(_constants2.METHOD_START_MESSAGE, {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'handleNetworkOnline'
            });
          case 2:
          case "end":
            return _context22.stop();
        }
      }, _callee22);
    })));
    it('mercury offline submits metrics and sets timestamp', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee23() {
      var mercuryOfflineCb;
      return _regenerator.default.wrap(function (_context23) {
        while (1) switch (_context23.prev = _context23.next) {
          case 0:
            mercuryOfflineCb = webex.internal.mercury.on.mock.calls[1][1];
            _context23.next = 1;
            return mercuryOfflineCb();
          case 1:
            expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Mercury down, waiting for connection to be up'), {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'handleMercuryOffline'
            });
            expect(callingClient['mercuryDownTimestamp']).toEqual(expect.any(String));
            expect(metricSpy).toHaveBeenCalledWith(_types4.METRIC_EVENT.CONNECTION_ERROR, _types4.CONNECTION_ACTION.MERCURY_DOWN, _types4.METRIC_TYPE.BEHAVIORAL, expect.any(String), '');
          case 2:
          case "end":
            return _context23.stop();
        }
      }, _callee23);
    })));
    it('handles reconnection with no active calls after network flap, once mercury comes back up', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee24() {
      var handleConnectionRestoreSpy, mercuryOnlineCb;
      return _regenerator.default.wrap(function (_context24) {
        while (1) switch (_context24.prev = _context24.next) {
          case 0:
            handleConnectionRestoreSpy = jest.spyOn(reg, 'handleConnectionRestoration');
            callingClient['isNetworkDown'] = true;
            callingClient['networkDownTimestamp'] = '2023-01-01T00:00:00.000Z';
            callingClient['networkUpTimestamp'] = '2023-01-01T00:01:00.000Z';
            mercuryOnlineCb = webex.internal.mercury.on.mock.calls[2][1];
            _context24.next = 1;
            return mercuryOnlineCb();
          case 1:
            // Run the interval once
            jest.advanceTimersByTime(_constants.NETWORK_FLAP_TIMEOUT + 100);
            _context24.next = 2;
            return flushPromises();
          case 2:
            expect(handleConnectionRestoreSpy).toHaveBeenCalledWith(true);
            expect(logSpy).toHaveBeenCalledWith('Network is up again, re-registering with Webex Calling if needed', {
              file: _constants.REGISTRATION_FILE,
              method: 'handleConnectionRestoration'
            });
            expect(deRegSpy).toHaveBeenCalledWith();
            expect(restoreSpy).toHaveBeenCalledWith('handleConnectionRestoration');
            expect(restartRegisterSpy).toHaveBeenCalledWith('handleConnectionRestoration');
            expect(registerSpy).toHaveBeenCalledWith('handleConnectionRestoration', [reg.getActiveMobiusUrl()]);
            expect(registerSpy).toHaveBeenCalledWith('handleConnectionRestoration', [_callingClientFixtures.primaryUrl]);
            expect(metricSpy).toHaveBeenCalledWith(_types4.METRIC_EVENT.CONNECTION_ERROR, _types4.CONNECTION_ACTION.NETWORK_FLAP, _types4.METRIC_TYPE.BEHAVIORAL, '2023-01-01T00:00:00.000Z', '2023-01-01T00:01:00.000Z');
          case 3:
          case "end":
            return _context24.stop();
        }
      }, _callee24);
    })));
    it('no reconnection for idle registration with no active calls after network flap, once mercury comes back up', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee25() {
      var handleConnectionRestoreSpy, mercuryOnlineCb;
      return _regenerator.default.wrap(function (_context25) {
        while (1) switch (_context25.prev = _context25.next) {
          case 0:
            handleConnectionRestoreSpy = jest.spyOn(reg, 'handleConnectionRestoration');
            callingClient['isNetworkDown'] = true;
            callingClient['networkDownTimestamp'] = '2023-01-01T00:00:00.000Z';
            callingClient['networkUpTimestamp'] = '2023-01-01T00:01:00.000Z';
            reg.setStatus(_types2.RegistrationStatus.IDLE);
            mercuryOnlineCb = webex.internal.mercury.on.mock.calls[2][1];
            _context25.next = 1;
            return mercuryOnlineCb();
          case 1:
            // Run the interval once
            jest.advanceTimersByTime(_constants.NETWORK_FLAP_TIMEOUT + 100);
            _context25.next = 2;
            return flushPromises();
          case 2:
            expect(handleConnectionRestoreSpy).not.toHaveBeenCalledWith(true);
            expect(logSpy).not.toHaveBeenCalledWith('Network is up again, re-registering with Webex Calling if needed', {
              file: _constants.REGISTRATION_FILE,
              method: 'handleConnectionRestoration'
            });
            expect(deRegSpy).not.toHaveBeenCalledWith();
            expect(restoreSpy).not.toHaveBeenCalledWith('handleConnectionRestoration');
            expect(restartRegisterSpy).not.toHaveBeenCalledWith('handleConnectionRestoration');
            expect(registerSpy).not.toHaveBeenCalledWith('handleConnectionRestoration', [reg.getActiveMobiusUrl()]);
            expect(registerSpy).not.toHaveBeenCalledWith('handleConnectionRestoration', [_callingClientFixtures.primaryUrl]);
            expect(metricSpy).toHaveBeenCalledWith(_types4.METRIC_EVENT.CONNECTION_ERROR, _types4.CONNECTION_ACTION.NETWORK_FLAP, _types4.METRIC_TYPE.BEHAVIORAL, '2023-01-01T00:00:00.000Z', '2023-01-01T00:01:00.000Z');
          case 3:
          case "end":
            return _context25.stop();
        }
      }, _callee25);
    })));
    it('handle calls status check once mercury comes back up after a network flap', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee26() {
      var call, callKeepaliveSpy, deleteSpy, mercuryOnlineCb;
      return _regenerator.default.wrap(function (_context26) {
        while (1) switch (_context26.prev = _context26.next) {
          case 0:
            callingClient['isNetworkDown'] = true;
            call = callingClient['callManager'].createCall();
            callKeepaliveSpy = jest.spyOn(call, 'postStatus').mockRejectedValueOnce(new Error('keepalive fail'));
            deleteSpy = jest.spyOn(call, 'delete');
            expect((0, _keys.default)(callingClient['callManager'].getActiveCalls()).length).toBe(1);
            mercuryOnlineCb = webex.internal.mercury.on.mock.calls[2][1];
            _context26.next = 1;
            return mercuryOnlineCb();
          case 1:
            expect(callKeepaliveSpy).toHaveBeenCalled();
            _context26.next = 2;
            return flushPromises();
          case 2:
            expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Call Keepalive failed'), {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'checkCallStatus'
            });
            expect(call['callStateMachine'].state.value).toBe('S_CALL_CLEARED');
            expect(deleteSpy).toHaveBeenCalled();
            expect((0, _keys.default)(reg.callManager.getActiveCalls()).length).toBe(0);
            expect(metricSpy).toHaveBeenCalledWith(_types4.METRIC_EVENT.CONNECTION_ERROR, _types4.CONNECTION_ACTION.NETWORK_FLAP, _types4.METRIC_TYPE.BEHAVIORAL, expect.any(String), expect.any(String));
          case 3:
          case "end":
            return _context26.stop();
        }
      }, _callee26);
    })));
    it('handle calls status check once mercury comes back up with stable network', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee27() {
      var call, callKeepaliveSpy, deleteSpy, mercuryOnlineCb;
      return _regenerator.default.wrap(function (_context27) {
        while (1) switch (_context27.prev = _context27.next) {
          case 0:
            call = callingClient['callManager'].createCall();
            callKeepaliveSpy = jest.spyOn(call, 'postStatus').mockRejectedValueOnce(new Error('keepalive fail'));
            deleteSpy = jest.spyOn(call, 'delete');
            expect((0, _keys.default)(callingClient['callManager'].getActiveCalls()).length).toBe(1);
            mercuryOnlineCb = webex.internal.mercury.on.mock.calls[2][1];
            _context27.next = 1;
            return mercuryOnlineCb();
          case 1:
            expect(callKeepaliveSpy).toHaveBeenCalled();
            _context27.next = 2;
            return flushPromises();
          case 2:
            expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Call Keepalive failed'), {
              file: _constants.CALLING_CLIENT_FILE,
              method: 'checkCallStatus'
            });
            expect(call['callStateMachine'].state.value).toBe('S_CALL_CLEARED');
            expect(deleteSpy).toHaveBeenCalled();
            expect((0, _keys.default)(reg.callManager.getActiveCalls()).length).toBe(0);
            expect(metricSpy).toHaveBeenCalledWith(_types4.METRIC_EVENT.CONNECTION_ERROR, _types4.CONNECTION_ACTION.MERCURY_UP, _types4.METRIC_TYPE.BEHAVIORAL, expect.any(String), expect.any(String));
          case 3:
          case "end":
            return _context27.stop();
        }
      }, _callee27);
    })));
  });

  // Calling related test cases
  describe('Calling tests', function () {
    var mutex = new _asyncMutex.Mutex();
    var userId = webex.internal.device.userId;
    var clientDeviceUri = webex.internal.device.url;
    var mobiusUris = (0, _Utils.filterMobiusUris)((0, _testUtil.getMobiusDiscoveryResponse)(), _registerFixtures.URL);
    var primaryMobiusUris = jest.fn(function () {
      return mobiusUris.primary;
    });
    var backupMobiusUris = jest.fn(function () {
      return mobiusUris.backup;
    });
    var callingClient;
    var line;
    beforeAll(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee28() {
      var calls;
      return _regenerator.default.wrap(function (_context28) {
        while (1) switch (_context28.prev = _context28.next) {
          case 0:
            _context28.next = 1;
            return (0, _CallingClient.createClient)(webex);
          case 1:
            callingClient = _context28.sent;
            line = new _line.default(userId, clientDeviceUri, mutex, primaryMobiusUris(), backupMobiusUris(), _types.LOGGER.INFO);
            calls = (0, _values.default)(callManager.getActiveCalls());
            calls.forEach(function (call) {
              call.end();
            });
          case 2:
          case "end":
            return _context28.stop();
        }
      }, _callee28);
    })));
    afterAll(function () {
      callingClient.removeAllListeners();
      callManager.removeAllListeners();
    });
    it('verify calling client object', function () {
      expect(callingClient.getSDKConnector().getWebex().internal.device.userId).toBe('8a67806f-fc4d-446b-a131-31e71ea5b0e9');
    });
    it('returns undefined when there is no connected call', function () {
      line.register();
      line.makeCall({
        address: '123456',
        type: _types2.CallType.URI
      });
      expect(callingClient.getConnectedCall()).toEqual(undefined);
    });
    it('returns the connected call', function () {
      line.register();
      var mockCall = line.makeCall({
        address: '1234',
        type: _types2.CallType.URI
      });
      var mockCall2 = line.makeCall({
        address: '5678',
        type: _types2.CallType.URI
      });
      // Connected call
      mockCall['connected'] = true;
      mockCall['earlyMedia'] = false;
      mockCall['callStateMachine'].state.value = 'S_CALL_ESTABLISHED';

      // Held call
      mockCall2['connected'] = true;
      mockCall2['held'] = true;
      mockCall2['earlyMedia'] = false;
      mockCall2['callStateMachine'].state.value = 'S_CALL_HOLD';
      var mockActiveCalls = {
        mockCorrelationId: mockCall,
        mockCorrelationId2: mockCall2
      };
      jest.spyOn(callManager, 'getActiveCalls').mockReturnValue(mockActiveCalls);
      expect(callingClient.getConnectedCall()).toEqual(mockCall);
    });
    it('returns all active calls', function () {
      callingClient.lineDict = {
        mockDeviceId: {
          lineId: 'mockLineId'
        },
        mockDeviceId2: {
          lineId: 'mockLineId2'
        }
      };
      var mockCall = line.makeCall({
        address: '1234',
        type: _types2.CallType.URI
      });
      var mockCall2 = line.makeCall({
        address: '5678',
        type: _types2.CallType.URI
      });
      var mockCall3 = line.makeCall({
        address: '9101',
        type: _types2.CallType.URI
      });
      mockCall.lineId = 'mockLineId';
      mockCall2.lineId = 'mockLineId2';
      mockCall3.lineId = 'mockLineId2';
      var mockActiveCalls = {
        mockCorrelationId: mockCall,
        mockCorrelationId2: mockCall2,
        mockCorrelationId3: mockCall3
      };
      jest.spyOn(callManager, 'getActiveCalls').mockReturnValue(mockActiveCalls);
      expect(callingClient.getActiveCalls()).toEqual({
        mockLineId: [mockCall],
        mockLineId2: [mockCall2, mockCall3]
      });
    });
  });
  describe('Call Session Event test', function () {
    var mockOn = webex.internal.mercury.on;
    var callingClient;
    beforeEach(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee29() {
      return _regenerator.default.wrap(function (_context29) {
        while (1) switch (_context29.prev = _context29.next) {
          case 0:
            _context29.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context29.sent;
          case 2:
          case "end":
            return _context29.stop();
        }
      }, _callee29);
    })));
    afterEach(function () {
      callingClient.removeAllListeners();
      callManager.removeAllListeners();
    });
    it('verify the recent user session event ', function (done) {
      expect.assertions(2);
      callingClient.on(_types3.CALLING_CLIENT_EVENT_KEYS.USER_SESSION_INFO, function (event) {
        expect(event.data).toEqual(_callRecordFixtures.MOCK_SESSION_EVENT.data);
        done();
      });
      expect(mockOn.mock.calls[0][0]).toEqual(_types3.MOBIUS_EVENT_KEYS.CALL_SESSION_EVENT_INCLUSIVE);
      var callSessionCallback = mockOn.mock.calls[0][1];
      callSessionCallback(_callRecordFixtures.MOCK_SESSION_EVENT);
    });
    it('drop the recent user session if there is no webex calling type', function (done) {
      expect.assertions(2);
      callingClient.on(_types3.CALLING_CLIENT_EVENT_KEYS.USER_SESSION_INFO, function (event) {
        expect(event.data.userSessions.userSessions.length).toEqual(1);
        done();
      });
      expect(mockOn.mock.calls[0][0]).toEqual(_types3.MOBIUS_EVENT_KEYS.CALL_SESSION_EVENT_INCLUSIVE);
      var callSessionCallback = mockOn.mock.calls[0][1];
      callSessionCallback(_callRecordFixtures.MOCK_MULTIPLE_SESSIONS_EVENT);
    });
  });
  describe('Mobius async_event routing', function () {
    var callingClient;
    var asyncEventCallback;
    var mobiusSocketMock;
    beforeEach(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee30() {
      var asyncEventOnCall;
      return _regenerator.default.wrap(function (_context30) {
        while (1) switch (_context30.prev = _context30.next) {
          case 0:
            webex.internal.device.features.developer.get = jest.fn().mockReturnValue({
              value: true
            });
            _request.APIRequest.resetInstance();
            _request.APIRequest.getInstance({
              webex: webex
            });
            mobiusSocketMock = jest.requireMock('../mobius-socket').getMobiusSocketInstance(webex);
            mobiusSocketMock.on.mockClear();
            mobiusSocketMock.off.mockClear();
            _context30.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context30.sent;
            asyncEventOnCall = mobiusSocketMock.on.mock.calls.find(function (call) {
              return call[0] === 'event:async_event';
            });
            asyncEventCallback = asyncEventOnCall[1];
          case 2:
          case "end":
            return _context30.stop();
        }
      }, _callee30);
    })));
    afterEach(function () {
      callingClient.removeAllListeners();
      callManager.removeAllListeners();
      webex.internal.device.features.developer.get = jest.fn().mockReturnValue({
        value: false
      });
    });
    it('routes mobius.* async events to callManager', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee31() {
      var callEventSpy;
      return _regenerator.default.wrap(function (_context31) {
        while (1) switch (_context31.prev = _context31.next) {
          case 0:
            callEventSpy = jest.spyOn(callingClient['callManager'], 'dequeueWsEvents').mockImplementation(function () {
              return undefined;
            });
            _context31.next = 1;
            return asyncEventCallback({
              type: 'async_event',
              data: {
                eventType: 'mobius.call',
                callId: 'fcf86aa5-5539-4c9f-8b72-667786ae9b6c',
                callUrl: 'https://mobius-a.wbx2.com/api/v1/calling/web/devices/d1/calls/c1',
                deviceId: 'd1',
                correlationId: 'corr-1'
              }
            });
          case 1:
            expect(callEventSpy).toHaveBeenCalledWith(expect.objectContaining({
              type: 'async_event',
              data: expect.objectContaining({
                eventType: 'mobius.call'
              })
            }));
          case 2:
          case "end":
            return _context31.stop();
        }
      }, _callee31);
    })));
  });
  describe('getDevices', function () {
    var callingClient;
    var primaryMobius = 'https://mobius.primary/api/v1/calling/web/';
    var backupMobius = 'https://mobius.backup/api/v1/calling/web/';
    beforeEach(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee32() {
      return _regenerator.default.wrap(function (_context32) {
        while (1) switch (_context32.prev = _context32.next) {
          case 0:
            _context32.next = 1;
            return (0, _CallingClient.createClient)(webex, {
              logger: {
                level: _types.LOGGER.INFO
              }
            });
          case 1:
            callingClient = _context32.sent;
            callingClient.primaryMobiusUris = [primaryMobius];
            callingClient.backupMobiusUris = [backupMobius];
            webex.request.mockClear();
          case 2:
          case "end":
            return _context32.stop();
        }
      }, _callee32);
    })));
    afterEach(function () {
      callingClient.removeAllListeners();
    });
    it('fetches devices for the provided userId', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee33() {
      var devices, responsePayload, response;
      return _regenerator.default.wrap(function (_context33) {
        while (1) switch (_context33.prev = _context33.next) {
          case 0:
            devices = [{
              deviceId: 'device-1',
              uri: 'https://mobius.test/api/v1/calling/web/devices/device-1',
              status: 'ACTIVE',
              lastSeen: '2024-01-01T00:00:00Z',
              addresses: [],
              clientDeviceUri: 'client-device-uri'
            }];
            responsePayload = {
              statusCode: 200,
              body: {
                userId: 'user-123',
                devices: devices
              }
            };
            webex.request.mockResolvedValue(responsePayload);
            _context33.next = 1;
            return callingClient.getDevices('user-123');
          case 1:
            response = _context33.sent;
            expect(webex.request).toHaveBeenCalledWith({
              uri: 'https://mobius.primary/api/v1/calling/web/devices?userid=user-123',
              method: _types2.HTTP_METHODS.GET,
              service: _types2.ALLOWED_SERVICES.MOBIUS,
              headers: (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _constants.CISCO_DEVICE_URL, webex.internal.device.url), _constants.SPARK_USER_AGENT, _constants.CALLING_USER_AGENT)
            });
            expect(response).toEqual(devices);
          case 2:
          case "end":
            return _context33.stop();
        }
      }, _callee33);
    })));
    it('falls back to backup Mobius when primary fails', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee34() {
      var devices, failurePayload, responsePayload, response, requestCalls;
      return _regenerator.default.wrap(function (_context34) {
        while (1) switch (_context34.prev = _context34.next) {
          case 0:
            devices = [{
              deviceId: 'device-2',
              uri: 'https://mobius.backup/api/v1/calling/web/devices/device-2',
              status: 'ACTIVE',
              lastSeen: '2024-01-01T00:00:00Z',
              addresses: [],
              clientDeviceUri: 'client-device-uri'
            }];
            failurePayload = {
              statusCode: 404
            };
            responsePayload = {
              statusCode: 200,
              body: {
                userId: 'user-123',
                devices: devices
              }
            };
            webex.request.mockRejectedValueOnce(failurePayload).mockResolvedValueOnce(responsePayload);
            _context34.next = 1;
            return callingClient.getDevices('user-123');
          case 1:
            response = _context34.sent;
            requestCalls = webex.request.mock.calls;
            expect(requestCalls[0][0]).toEqual({
              uri: 'https://mobius.primary/api/v1/calling/web/devices?userid=user-123',
              method: _types2.HTTP_METHODS.GET,
              service: _types2.ALLOWED_SERVICES.MOBIUS,
              headers: (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _constants.CISCO_DEVICE_URL, webex.internal.device.url), _constants.SPARK_USER_AGENT, _constants.CALLING_USER_AGENT)
            });
            expect(requestCalls[1][0]).toEqual({
              uri: 'https://mobius.backup/api/v1/calling/web/devices?userid=user-123',
              method: _types2.HTTP_METHODS.GET,
              service: _types2.ALLOWED_SERVICES.MOBIUS,
              headers: (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _constants.CISCO_DEVICE_URL, webex.internal.device.url), _constants.SPARK_USER_AGENT, _constants.CALLING_USER_AGENT)
            });
            expect(response).toEqual(devices);
          case 2:
          case "end":
            return _context34.stop();
        }
      }, _callee34);
    })));
  });
  describe('windowsChromiumIceWarmup', function () {
    var origRTCPeerConnection;
    beforeAll(function () {
      var _Class;
      origRTCPeerConnection = global.RTCPeerConnection;
      // Minimal mock for RTCPeerConnection
      global.RTCPeerConnection = (_Class = /*#__PURE__*/function () {
        function _Class() {
          (0, _classCallCheck2.default)(this, _Class);
          (0, _defineProperty2.default)(this, "iceGatheringState", 'complete');
          (0, _defineProperty2.default)(this, "localDescription", null);
          (0, _defineProperty2.default)(this, "remoteDescription", null);
          (0, _defineProperty2.default)(this, "onicecandidate", null);
          this.constructor.instances.push(this);
        }
        return (0, _createClass2.default)(_Class, [{
          key: "createDataChannel",
          value: function createDataChannel() {
            return {};
          }
        }, {
          key: "addTransceiver",
          value: function addTransceiver() {
            return {};
          }
        }, {
          key: "createOffer",
          value: function createOffer() {
            return _promise.default.resolve({
              sdp: 'offer',
              type: 'offer'
            });
          }
        }, {
          key: "setLocalDescription",
          value: function setLocalDescription(desc) {
            this.localDescription = desc;
            return _promise.default.resolve();
          }
        }, {
          key: "setRemoteDescription",
          value: function setRemoteDescription(desc) {
            this.remoteDescription = desc;
            return _promise.default.resolve();
          }
        }, {
          key: "createAnswer",
          value: function createAnswer() {
            return _promise.default.resolve({
              sdp: 'answer',
              type: 'answer'
            });
          }
        }, {
          key: "addIceCandidate",
          value: function addIceCandidate() {
            return _promise.default.resolve();
          }
        }, {
          key: "close",
          value: function close() {}
        }, {
          key: "addEventListener",
          value: function addEventListener() {}
        }, {
          key: "removeEventListener",
          value: function removeEventListener() {}
        }]);
      }(), (0, _defineProperty2.default)(_Class, "instances", []), _Class);
    });
    afterAll(function () {
      global.RTCPeerConnection = origRTCPeerConnection;
    });
    it('should complete without throwing', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee35() {
      return _regenerator.default.wrap(function (_context35) {
        while (1) switch (_context35.prev = _context35.next) {
          case 0:
            _context35.next = 1;
            return expect((0, _windowsChromiumIceWarmupUtils.default)({})).resolves.not.toThrow();
          case 1:
          case "end":
            return _context35.stop();
        }
      }, _callee35);
    })));
  });
});
//# sourceMappingURL=CallingClient.test.js.map
