"use strict";

var _typeof = require("@babel/runtime-corejs2/helpers/typeof");
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");
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));
var _values = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/values"));
var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));
var _Utils = _interopRequireWildcard(require("../../common/Utils"));
var utils = _Utils;
var _types = require("../../common/types");
var _testUtil = require("../../common/testUtil");
var _callManager = require("./callManager");
var _types2 = require("./types");
var _call = require("./call");
var _Logger = _interopRequireDefault(require("../../Logger"));
var _types3 = require("../../Events/types");
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 _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = _Object$defineProperty) && _Object$getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable dot-notation */

var webex = (0, _testUtil.getTestUtilsWebex)();
var defaultServiceIndicator = _types.ServiceIndicator.CALLING;
var mediaEvent = {
  id: '73e6a2b2-968c-44ea-a536-e7702722f8d8',
  data: {
    message: {
      messageType: 'OFFER',
      sdp: 'v=0\r\no=BroadWorks 175625 1653906127914 IN IP4 207.182.171.180\r\ns=-\r\nc=IN IP4 207.182.171.180\r\nt=0 0\r\na=ice-lite\r\nm=audio 19564 UDP/TLS/RTP/SAVPF 99 9 0 8 18 102 101\r\na=sendrecv\r\na=rtpmap:99 opus/48000/2\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:18 G729/8000\r\na=fmtp:18 annexb=no\r\na=rtpmap:102 iLBC/8000\r\na=fmtp:102 mode=30\r\na=rtpmap:101 telephone-event/8000\r\na=rtcp-mux\r\na=setup:actpass\r\na=ssrc:379289707 cname:HC3h2tromqGgnGaf\r\na=ice-ufrag:mLbW\r\na=ice-pwd:Hct9MYtML1sedttd8fLCg9aJ\r\na=fingerprint:sha-256 5E:F5:3D:98:57:03:D7:73:8F:C3:D4:FC:EC:FE:7F:4D:04:D8:EE:2A:29:C4:9F:35:C5:0F:D1:2D:CE:E4:AE:AA\r\na=candidate:mse 1 UDP 2130706431 207.182.171.180 19564 typ host\r\na=candidate:mse 2 UDP 2130706430 207.182.171.180 19565 typ host',
      seq: 1,
      version: '2'
    },
    callId: 'f2e89262-7d9a-489f-b65d-3b56a31c7bfe',
    callUrl: '[https://wdm-intb.ciscospark.com/wdm/api/v1/devices/14ef3832-a7af-4457-a660-fd1918d627d0]',
    deviceId: '375b8503-f716-3407-853b-cd9a8c4419a7',
    correlationId: '',
    eventType: 'mobius.media'
  },
  timestamp: 1653906128188,
  trackingId: 'ROUTER_62949AD0-DB6E-01BB-595A-03158964595A',
  alertType: 'full',
  headers: {},
  sequenceNumber: 7,
  filterMessage: false
};
var setupEvent = {
  id: '3ee919c7-202d-4f8c-9b74-e5ee8a693dfa',
  data: {
    callerId: {
      'x-broadworks-remote-party-info': 'userId="hkkcq0ekby@64941297.int10.bcld.webex.com";userDn="tel:+12142865895;ext=5008;country-code=1";externalId=652fe0c7-05ce-4acd-8bda-9a080830187f',
      from: '"Bob Marley" <sip:5008@207.182.171.130;user=phone>;tag=379221777-1653906128003-'
    },
    callId: 'f2e89262-7d9a-489f-b65d-3b56a31c7bfe',
    callUrl: '[https://wdm-intb.ciscospark.com/wdm/api/v1/devices/14ef3832-a7af-4457-a660-fd1918d627d0]',
    deviceId: '375b8503-f716-3407-853b-cd9a8c4419a7',
    correlationId: '',
    eventType: 'mobius.call',
    broadworksCorrelationInfo: 'Sample_broadworksCorrelationInfo'
  },
  timestamp: 1653906128159,
  trackingId: 'ROUTER_62949AD0-DB6E-01BB-595A-03158964595A',
  alertType: 'full',
  headers: {},
  sequenceNumber: 6,
  filterMessage: false
};
var disconnectEvent = {
  id: 'f3e37504-5867-48ea-8d67-4e82b3ce1755',
  data: {
    causecode: 0,
    cause: 'Normal disconnect',
    callId: 'cbfe802c-cc8d-407f-863d-0abf8d6cc497',
    callUrl: '[https://wdm-intb.ciscospark.com/wdm/api/v1/devices/5691641c-7f0c-47a4-b248-e585ebcf653d]',
    deviceId: 'b9270663-54c8-3540-b01f-ed807dc5f9e8',
    correlationId: '',
    eventType: 'mobius.calldisconnected'
  },
  timestamp: 1653925625934,
  trackingId: 'NA_fe7efbbc-de52-438c-a6c3-58e96db230ba',
  alertType: 'full',
  headers: {},
  sequenceNumber: 6,
  filterMessage: false
};
var registrationDownEvent = {
  type: 'async_event',
  trackingId: 'SRV_bb000000-0000-0000-0000-000000000007',
  eventId: 'a7b8c9d0-e1f2-3456-abcd-567890123456',
  data: {
    eventType: 'registration.down',
    deviceInfo: {
      userId: '44533573-f6aa-429d-b4fe-58aa04a2b636',
      device: {
        deviceId: '334f3d50-1d26-4712-93f1-4972390cc565',
        uri: 'https://mobius-a.wbx2.com/api/v1/calling/web/devices/334f3d50-1d26-4712-93f1-4972390cc565',
        status: 'inactive'
      }
    }
  }
};
var deviceId = '55dfb53f-bed2-36da-8e85-cee7f02aa68e';
var dest = {
  type: _types.CallType.URI,
  address: 'tel:5003'
};
var successResponseBody = {
  statusCode: 200,
  body: {
    device: {
      deviceId: '8a67806f-fc4d-446b-a131-31e71ea5b010',
      correlationId: '8a67806f-fc4d-446b-a131-31e71ea5b011'
    },
    callId: '8a67806f-fc4d-446b-a131-31e71ea5b020',
    callData: {
      callState: _types2.MobiusCallState.PROCEEDING
    }
  }
};
var mockLineId = 'e4e8ee2a-a154-4e52-8f11-ef4cde2dce72';
var mockLine = {
  lineId: mockLineId
};
describe('Call Manager Tests with respect to calls', function () {
  var dummyResponse = {
    statusCode: 200,
    body: {
      device: {
        deviceId: '8a67806f-fc4d-446b-a131-31e71ea5b010',
        correlationId: '8a67806f-fc4d-446b-a131-31e71ea5b011'
      }
    }
  };
  var patchMock = jest.spyOn(_call.Call.prototype, 'patch');
  var setDisconnectReasonMock = jest.spyOn(_call.Call.prototype, 'setDisconnectReason');
  var deleteCallMock = jest.spyOn(_call.Call.prototype, 'delete');
  var initMediaConnectionMock = jest.spyOn(_call.Call.prototype, 'initMediaConnection');
  var mediaRoapEventsListenerMock = jest.spyOn(_call.Call.prototype, 'mediaRoapEventsListener');
  var mediaTrackListenerMock = jest.spyOn(_call.Call.prototype, 'mediaTrackListener');
  var postMediaMock = jest.spyOn(_call.Call.prototype, 'postMedia');
  deleteCallMock.mockResolvedValue(dummyResponse); // Both are using dummy response
  setDisconnectReasonMock.mockReturnValue({});
  initMediaConnectionMock.mockReturnValue({});
  mediaRoapEventsListenerMock.mockReturnValue({});
  mediaTrackListenerMock.mockReturnValue({});
  postMediaMock.mockResolvedValue({});
  var callManager;
  beforeEach(function () {
    callManager = (0, _callManager.getCallManager)(webex, defaultServiceIndicator);
    callManager.removeAllListeners(_types3.LINE_EVENT_KEYS.INCOMING_CALL);
    /* expect 0 calls at the beginning of each test as we are clearing calls at the end of every test case */
    expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(0);
  });
  afterEach(function () {
    /* lets clear all calls at the end of every test case */
    var calls = (0, _values.default)(callManager.getActiveCalls());
    calls.forEach(function (call) {
      call.end();
    });
  });
  it('check instance of call manager', function () {
    expect(callManager).toBeTruthy();
  });
  it('Check whether callManager is singleton', function () {
    var callManagerNew = (0, _callManager.getCallManager)(webex, defaultServiceIndicator);
    expect(callManager).toMatchObject(callManagerNew);
  });
  it('create a call using call manager', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
    var logSpy, call;
    return _regenerator.default.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          callManager.updateLine('8a67806f-fc4d-446b-a131-31e71ea5b010', mockLine);
          webex.request.mockReturnValueOnce({
            statusCode: 200,
            body: {
              device: {
                deviceId: '8a67806f-fc4d-446b-a131-31e71ea5b010',
                correlationId: '8a67806f-fc4d-446b-a131-31e71ea5b011'
              },
              callId: '8a67806f-fc4d-446b-a131-31e71ea5b020',
              callData: {
                callState: _types2.MobiusCallState.PROCEEDING
              }
            }
          });
          logSpy = jest.spyOn(_Logger.default, 'log');
          expect(callManager).toBeTruthy();
          _context.next = 1;
          return callManager.createCall(_types.CallDirection.OUTBOUND, deviceId, mockLineId, dest);
        case 1:
          call = _context.sent;
          call.setCallId('8a67806f-fc4d-446b-a131-31e71ea5b020');
          expect(call).toBeTruthy();
          expect(call.getCallId()).toStrictEqual('8a67806f-fc4d-446b-a131-31e71ea5b020');
          expect(call.lineId).toStrictEqual(mockLineId);
          expect(logSpy).toHaveBeenCalledWith('Creating call object', {});
        case 2:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })));
  it('Accept an incoming call from Mobius where Call Setup was the first message', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
    return _regenerator.default.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          callManager.updateLine('375b8503-f716-3407-853b-cd9a8c4419a7', mockLine);
          callManager.on(_types3.LINE_EVENT_KEYS.INCOMING_CALL, function (callObj) {
            expect(callObj.getCallId()).toStrictEqual(setupEvent.data.callId);
            expect(callObj.getBroadworksCorrelationInfo()).toStrictEqual(setupEvent.data.broadworksCorrelationInfo);
            expect(callObj.lineId).toStrictEqual(mockLineId);
          });
          patchMock.mockResolvedValue(dummyResponse);
          _context2.next = 1;
          return callManager['dequeueWsEvents'](setupEvent);
        case 1:
          _context2.next = 2;
          return (0, _Utils.waitForMsecs)(50);
        case 2:
          _context2.next = 3;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 3:
          _context2.next = 4;
          return (0, _Utils.waitForMsecs)(50);
        case 4:
          expect(patchMock).toHaveBeenCalledWith(_types2.MobiusCallState.ALERTING);
          /* setUp event should create the call and count will be 1 for new call */
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(1);
        case 5:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  })));
  it('Accept an incoming call from Mobius where Media Event was the first message', /*#__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:
          callManager.updateLine('8a67806f-fc4d-446b-a131-31e71ea5b010', mockLine);
          patchMock.mockResolvedValue(dummyResponse);
          callManager.on(_types3.LINE_EVENT_KEYS.INCOMING_CALL, function (callObj) {
            expect(callObj.getCallId()).toStrictEqual(setupEvent.data.callId);
            expect(callObj['remoteRoapMessage'].sdp).toStrictEqual(mediaEvent.data.message.sdp);
          });
          _context3.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          _context3.next = 2;
          return callManager['dequeueWsEvents'](setupEvent);
        case 2:
          expect(patchMock).toHaveBeenCalledWith(_types2.MobiusCallState.ALERTING);
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(1);
        case 3:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  })));
  it('Disconnect a call if received a Call Disconnect event', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4() {
    var call;
    return _regenerator.default.wrap(function (_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          webex.request.mockReturnValueOnce(successResponseBody);

          /* lets add a call to disconnect it later */
          _context4.next = 1;
          return callManager.createCall(dest, _types.CallDirection.OUTBOUND, deviceId, mockLineId);
        case 1:
          call = _context4.sent;
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(1);
          /* clear the last added call */

          patchMock.mockResolvedValue(dummyResponse);
          disconnectEvent.data.correlationId = call.getCorrelationId();
          callManager['dequeueWsEvents'](disconnectEvent);

          /* Add a small delay , to simulate sending of Delete request and clearing from Call records */
          _context4.next = 2;
          return (0, _Utils.waitForMsecs)(50);
        case 2:
          expect(deleteCallMock).toHaveBeenCalled();
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(0);
        case 3:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  })));
  it('Do not Disconnect a call if call has been disconnected already', /*#__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:
          webex.request.mockReturnValueOnce(successResponseBody);

          /* lets add a call to disconnect it later */
          _context5.next = 1;
          return callManager.createCall(_types.CallDirection.OUTBOUND, deviceId, mockLineId, dest);
        case 1:
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(1);
          /* clear the last added call */

          patchMock.mockResolvedValue(dummyResponse);
          disconnectEvent.data.correlationId = '1234';
          callManager['dequeueWsEvents'](disconnectEvent);

          /* Add a small delay , to simulate sending of Delete request and clearing from Call records */
          _context5.next = 2;
          return (0, _Utils.waitForMsecs)(50);
        case 2:
          expect(deleteCallMock).not.toHaveBeenCalled();
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(1);
        case 3:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  })));
  it('Accept an incoming call but Outgoing patch request fails', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee6() {
    var _mediaEvent$data$mess, _mediaEvent$data$mess2, _mediaEvent$data$mess3;
    var errorSpy, logSpy, uploadLogsSpy;
    return _regenerator.default.wrap(function (_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          callManager.updateLine('8a67806f-fc4d-446b-a131-31e71ea5b010', mockLine);
          /* Intentionally failing the Patch with 503 */
          dummyResponse.statusCode = 503;
          patchMock.mockRejectedValue(dummyResponse);
          errorSpy = jest.spyOn(_Logger.default, 'error');
          logSpy = jest.spyOn(_Logger.default, 'log');
          uploadLogsSpy = jest.spyOn(utils, 'uploadLogs').mockResolvedValue();
          _context6.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          _context6.next = 2;
          return (0, _Utils.waitForMsecs)(50);
        case 2:
          _context6.next = 3;
          return callManager['dequeueWsEvents'](setupEvent);
        case 3:
          _context6.next = 4;
          return (0, _Utils.waitForMsecs)(50);
        case 4:
          expect(patchMock).toHaveBeenCalledWith(_types2.MobiusCallState.ALERTING);
          expect(errorSpy).toHaveBeenCalledWith("Failed to signal call progression: ".concat((0, _stringify.default)(dummyResponse)), {
            file: 'call',
            method: 'handleOutgoingCallAlerting'
          });
          expect(logSpy).toHaveBeenCalledWith("Received call media mobiusEvent for call: ".concat(mediaEvent.data.correlationId), expect.objectContaining({
            file: 'callManager',
            method: 'dequeueWsEvents'
          }));
          expect(logSpy).toHaveBeenCalledWith("ROAP message from mobius with type:  ".concat((_mediaEvent$data$mess = mediaEvent.data.message) === null || _mediaEvent$data$mess === void 0 ? void 0 : _mediaEvent$data$mess.messageType, ", seq: ").concat((_mediaEvent$data$mess2 = mediaEvent.data.message) === null || _mediaEvent$data$mess2 === void 0 ? void 0 : _mediaEvent$data$mess2.seq, " , version: ").concat((_mediaEvent$data$mess3 = mediaEvent.data.message) === null || _mediaEvent$data$mess3 === void 0 ? void 0 : _mediaEvent$data$mess3.version), expect.objectContaining({
            file: 'callManager',
            method: 'dequeueWsEvents'
          }));
          expect(uploadLogsSpy).toHaveBeenCalled();
          /* No calls should have been added as call progress failed */
          expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(0);
        case 5:
        case "end":
          return _context6.stop();
      }
    }, _callee6);
  })));
  it('Walk through an End to End call', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee8() {
    var call;
    return _regenerator.default.wrap(function (_context8) {
      while (1) switch (_context8.prev = _context8.next) {
        case 0:
          callManager.updateLine('8a67806f-fc4d-446b-a131-31e71ea5b010', mockLine);
          callManager.on(_types3.LINE_EVENT_KEYS.INCOMING_CALL, /*#__PURE__*/function () {
            var _ref8 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee7(callObj) {
              var mediaSpy, mediaClose, track;
              return _regenerator.default.wrap(function (_context7) {
                while (1) switch (_context7.prev = _context7.next) {
                  case 0:
                    expect(callObj.getCallId()).toStrictEqual(setupEvent.data.callId);
                    call = callObj;
                    _context7.next = 1;
                    return (0, _Utils.waitForMsecs)(50);
                  case 1:
                    mediaSpy = jest.spyOn(call['mediaConnection'], 'roapMessageReceived');
                    mediaClose = jest.spyOn(call['mediaConnection'], 'close').mockReturnValue({});
                    expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(3);
                    expect(call['callStateMachine'].state.value).toStrictEqual('S_SEND_CALL_PROGRESS');
                    expect(patchMock).toHaveBeenCalledWith(_types2.MobiusCallState.ALERTING);

                    /* Receive ROAP Offer */
                    _context7.next = 2;
                    return callManager['dequeueWsEvents'](mediaEvent);
                  case 2:
                    _context7.next = 3;
                    return (0, _Utils.waitForMsecs)(50);
                  case 3:
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_RECV_ROAP_OFFER');
                    track = {};
                    /* User answers the call */
                    _context7.next = 4;
                    return call.answer({
                      localAudioTrack: track
                    });
                  case 4:
                    _context7.next = 5;
                    return (0, _Utils.waitForMsecs)(50);
                  case 5:
                    expect(call['callStateMachine'].state.value).toStrictEqual('S_SEND_CALL_CONNECT');
                    expect(patchMock).toHaveBeenCalledWith(_types2.MobiusCallState.CONNECTED);
                    expect(mediaSpy).toHaveBeenCalled(); /* We pass the offer to media connection */

                    /* We are manually sending this event , ideally it will sent by MediaConnection. */
                    call['sendMediaStateMachineEvt']({
                      type: 'E_SEND_ROAP_ANSWER'
                    });
                    _context7.next = 6;
                    return (0, _Utils.waitForMsecs)(50);
                  case 6:
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_SEND_ROAP_ANSWER');

                    /* Simulate ROAP_OK */
                    mediaEvent.data.message.messageType = 'OK';
                    _context7.next = 7;
                    return callManager['dequeueWsEvents'](mediaEvent);
                  case 7:
                    _context7.next = 8;
                    return (0, _Utils.waitForMsecs)(50);
                  case 8:
                    expect(mediaSpy).toHaveBeenCalled();
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_ROAP_OK');
                    expect(call['callStateMachine'].state.value).toStrictEqual('S_CALL_ESTABLISHED');

                    /* Simulate ROAP Offer_request */
                    mediaEvent.data.message.messageType = 'OFFER_REQUEST';
                    _context7.next = 9;
                    return callManager['dequeueWsEvents'](mediaEvent);
                  case 9:
                    _context7.next = 10;
                    return (0, _Utils.waitForMsecs)(50);
                  case 10:
                    expect(mediaSpy).toHaveBeenCalled();

                    /* We are manually sending this event , ideally it will sent by Media Connection. */
                    call['sendMediaStateMachineEvt']({
                      type: 'E_SEND_ROAP_OFFER'
                    });
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_SEND_ROAP_OFFER');

                    /* Simulate ROAP Answer */
                    mediaEvent.data.message.messageType = 'ANSWER';
                    _context7.next = 11;
                    return callManager['dequeueWsEvents'](mediaEvent);
                  case 11:
                    _context7.next = 12;
                    return (0, _Utils.waitForMsecs)(50);
                  case 12:
                    expect(mediaSpy).toHaveBeenCalled();
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_ROAP_OK');
                    expect(call['callStateMachine'].state.value).toStrictEqual('S_CALL_ESTABLISHED');

                    /* Start Call disconnect */
                    disconnectEvent.data.correlationId = call.getCorrelationId();
                    callManager['dequeueWsEvents'](disconnectEvent);
                    _context7.next = 13;
                    return (0, _Utils.waitForMsecs)(50);
                  case 13:
                    expect(deleteCallMock).toHaveBeenCalled();
                    expect(mediaClose).toHaveBeenCalled();
                    expect(call['mediaStateMachine'].state.value).toStrictEqual('S_ROAP_TEARDOWN');
                    expect(call['callStateMachine'].state.value).toStrictEqual('S_CALL_CLEARED');
                    expect((0, _keys.default)(callManager.getActiveCalls()).length).toBe(2);
                  case 14:
                  case "end":
                    return _context7.stop();
                }
              }, _callee7);
            }));
            return function (_x) {
              return _ref8.apply(this, arguments);
            };
          }());
          patchMock.mockResolvedValue(dummyResponse);
          _context8.next = 1;
          return callManager['dequeueWsEvents'](setupEvent);
        case 1:
        case "end":
          return _context8.stop();
      }
    }, _callee8);
  })));
});
describe('Coverage for Events listener', function () {
  var callManager;
  var call;
  var dummyCallId = '8a67806f-fc4d-4469-a131-31e71ec5b011';
  webex.request.mockReturnValueOnce({
    statusCode: 200,
    body: {
      device: {
        deviceId: '8a67806f-fc4d-446b-a131-31e71ea5b010',
        correlationId: '8a67806f-fc4d-446b-a131-31e71ea5b011'
      },
      callId: '8a67806f-fc4d-446b-a131-31e71ea5b020',
      callData: {
        callState: _types2.MobiusCallState.PROCEEDING
      }
    }
  });
  beforeEach(function () {
    jest.clearAllMocks();
    callManager = (0, _callManager.getCallManager)(webex, defaultServiceIndicator);
    callManager.removeAllListeners(_types3.LINE_EVENT_KEYS.INCOMING_CALL);
    call = callManager.createCall(_types.CallDirection.OUTBOUND, deviceId, mockLineId, dest);
    call.setCallId(dummyCallId);
    setupEvent.data.correlationId = call.getCorrelationId();
  });
  var funcSpy = jest.spyOn(_call.Call.prototype, 'sendMediaStateMachineEvt');
  var callSpy = jest.spyOn(_call.Call.prototype, 'sendCallStateMachineEvt');
  var logSpy = jest.spyOn(_Logger.default, 'log');
  it('When Offer is received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee9() {
    var eventData;
    return _regenerator.default.wrap(function (_context9) {
      while (1) switch (_context9.prev = _context9.next) {
        case 0:
          mediaEvent.data.callId = dummyCallId;
          jest.clearAllMocks();
          _context9.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          eventData = {
            data: mediaEvent.data.message,
            type: 'E_RECV_ROAP_OFFER'
          };
          expect(funcSpy).toHaveBeenCalledWith(eventData);
        case 2:
        case "end":
          return _context9.stop();
      }
    }, _callee9);
  })));
  it('When Answer is received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee0() {
    var eventData;
    return _regenerator.default.wrap(function (_context0) {
      while (1) switch (_context0.prev = _context0.next) {
        case 0:
          mediaEvent.data.message.messageType = 'ANSWER';
          jest.clearAllMocks();
          _context0.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          eventData = {
            data: mediaEvent.data.message,
            type: 'E_RECV_ROAP_ANSWER'
          };
          expect(funcSpy).toHaveBeenCalledWith(eventData);
        case 2:
        case "end":
          return _context0.stop();
      }
    }, _callee0);
  })));
  it('When Offer Request is received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee1() {
    var eventData;
    return _regenerator.default.wrap(function (_context1) {
      while (1) switch (_context1.prev = _context1.next) {
        case 0:
          mediaEvent.data.message.messageType = 'OFFER_REQUEST';
          jest.clearAllMocks();
          _context1.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          eventData = {
            data: mediaEvent.data.message,
            type: 'E_RECV_ROAP_OFFER_REQUEST'
          };
          expect(funcSpy).toHaveBeenCalledWith(eventData);
        case 2:
        case "end":
          return _context1.stop();
      }
    }, _callee1);
  })));
  it('When OK is received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee10() {
    var mediaOK, eventData;
    return _regenerator.default.wrap(function (_context10) {
      while (1) switch (_context10.prev = _context10.next) {
        case 0:
          mediaEvent.data.message.messageType = 'OK';
          jest.clearAllMocks();
          _context10.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          mediaOK = {
            received: true,
            message: mediaEvent.data.message
          };
          eventData = {
            data: mediaOK,
            type: 'E_ROAP_OK'
          };
          expect(funcSpy).toHaveBeenCalledWith(eventData);
        case 2:
        case "end":
          return _context10.stop();
      }
    }, _callee10);
  })));
  it('When Error is Received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee11() {
    var _mediaEvent$data$mess4, _mediaEvent$data$mess5, _mediaEvent$data$mess6, _mediaEvent$data$mess7;
    var infoSpy;
    return _regenerator.default.wrap(function (_context11) {
      while (1) switch (_context11.prev = _context11.next) {
        case 0:
          mediaEvent.data.message.messageType = 'ERROR';
          jest.clearAllMocks();
          infoSpy = jest.spyOn(_Logger.default, 'info');
          _context11.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          expect(logSpy).toHaveBeenCalledWith("Received call media mobiusEvent for call: ".concat(mediaEvent.data.correlationId), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(logSpy).toHaveBeenCalledWith("ROAP message from mobius with type:  ".concat((_mediaEvent$data$mess4 = mediaEvent.data.message) === null || _mediaEvent$data$mess4 === void 0 ? void 0 : _mediaEvent$data$mess4.messageType, ", seq: ").concat((_mediaEvent$data$mess5 = mediaEvent.data.message) === null || _mediaEvent$data$mess5 === void 0 ? void 0 : _mediaEvent$data$mess5.seq, " , version: ").concat((_mediaEvent$data$mess6 = mediaEvent.data.message) === null || _mediaEvent$data$mess6 === void 0 ? void 0 : _mediaEvent$data$mess6.version), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(logSpy).toHaveBeenCalledWith('Received Error...', {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(infoSpy).toHaveBeenCalledWith("SDP from mobius ".concat((_mediaEvent$data$mess7 = mediaEvent.data.message) === null || _mediaEvent$data$mess7 === void 0 ? void 0 : _mediaEvent$data$mess7.sdp), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
        case 2:
        case "end":
          return _context11.stop();
      }
    }, _callee11);
  })));
  it('When Unknown event is Received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee12() {
    var _mediaEvent$data$mess8, _mediaEvent$data$mess9, _mediaEvent$data$mess0, _mediaEvent$data$mess1;
    var infoSpy;
    return _regenerator.default.wrap(function (_context12) {
      while (1) switch (_context12.prev = _context12.next) {
        case 0:
          mediaEvent.data.message.messageType = 'UNKNOWN';
          jest.clearAllMocks();
          infoSpy = jest.spyOn(_Logger.default, 'info');
          _context12.next = 1;
          return callManager['dequeueWsEvents'](mediaEvent);
        case 1:
          expect(logSpy).toHaveBeenCalledWith("Received call media mobiusEvent for call: ".concat(mediaEvent.data.correlationId), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(logSpy).toHaveBeenCalledWith("ROAP message from mobius with type:  ".concat((_mediaEvent$data$mess8 = mediaEvent.data.message) === null || _mediaEvent$data$mess8 === void 0 ? void 0 : _mediaEvent$data$mess8.messageType, ", seq: ").concat((_mediaEvent$data$mess9 = mediaEvent.data.message) === null || _mediaEvent$data$mess9 === void 0 ? void 0 : _mediaEvent$data$mess9.seq, " , version: ").concat((_mediaEvent$data$mess0 = mediaEvent.data.message) === null || _mediaEvent$data$mess0 === void 0 ? void 0 : _mediaEvent$data$mess0.version), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(logSpy).toHaveBeenCalledWith('Unknown Media mobiusEvent: UNKNOWN ', {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
          expect(infoSpy).toHaveBeenCalledWith("SDP from mobius ".concat((_mediaEvent$data$mess1 = mediaEvent.data.message) === null || _mediaEvent$data$mess1 === void 0 ? void 0 : _mediaEvent$data$mess1.sdp), {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
        case 2:
        case "end":
          return _context12.stop();
      }
    }, _callee12);
  })));
  it('When Progress/Connect event is Received', /*#__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:
          setupEvent.data.eventType = 'mobius.callprogress';
          _context13.next = 1;
          return callManager['dequeueWsEvents'](setupEvent);
        case 1:
          expect(callSpy).toHaveBeenCalledWith({
            type: 'E_RECV_CALL_PROGRESS',
            data: setupEvent.data
          });
        case 2:
        case "end":
          return _context13.stop();
      }
    }, _callee13);
  })));
  it('Silently discard an event in the state machine', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee14() {
    var connectEvent;
    return _regenerator.default.wrap(function (_context14) {
      while (1) switch (_context14.prev = _context14.next) {
        case 0:
          call['callStateMachine'].state.value = 'S_SEND_CALL_CONNECT';
          expect(call['callStateMachine'].state.value).toStrictEqual('S_SEND_CALL_CONNECT');
          connectEvent = JSON.parse((0, _stringify.default)(setupEvent));
          connectEvent.data.eventType = 'mobius.callconnected';
          _context14.next = 1;
          return callManager['dequeueWsEvents'](connectEvent);
        case 1:
          /* There should not be any state change */
          expect(call['callStateMachine'].state.value).toStrictEqual('S_SEND_CALL_CONNECT');
        case 2:
        case "end":
          return _context14.stop();
      }
    }, _callee14);
  })));
  it('Silently discard an ROAP_ANSWER after being in ROAP_OK state', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee15() {
    var answerEvent;
    return _regenerator.default.wrap(function (_context15) {
      while (1) switch (_context15.prev = _context15.next) {
        case 0:
          call['mediaStateMachine'].state.value = 'S_ROAP_OK';
          expect(call['mediaStateMachine'].state.value).toStrictEqual('S_ROAP_OK');
          answerEvent = JSON.parse((0, _stringify.default)(mediaEvent));
          answerEvent.data.message.messageType = 'ANSWER';
          _context15.next = 1;
          return callManager['dequeueWsEvents'](answerEvent);
        case 1:
          /* There should not be any state change */
          expect(call['mediaStateMachine'].state.value).toStrictEqual('S_ROAP_OK');
        case 2:
        case "end":
          return _context15.stop();
      }
    }, _callee15);
  })));
  it('When Unknown Call event is Received', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee16() {
    return _regenerator.default.wrap(function (_context16) {
      while (1) switch (_context16.prev = _context16.next) {
        case 0:
          setupEvent.data.eventType = 'mobius.callunknown';
          jest.clearAllMocks();
          _context16.next = 1;
          return callManager['dequeueWsEvents'](setupEvent);
        case 1:
          expect(logSpy).toHaveBeenCalledWith('Unknown Call Event mobiusEvent: mobius.callunknown', {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
        case 2:
        case "end":
          return _context16.stop();
      }
    }, _callee16);
  })));
  it('Handles registration down event without routing to call state machine', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee17() {
    return _regenerator.default.wrap(function (_context17) {
      while (1) switch (_context17.prev = _context17.next) {
        case 0:
          jest.clearAllMocks();
          _context17.next = 1;
          return callManager['dequeueWsEvents'](registrationDownEvent);
        case 1:
          expect(callSpy).not.toHaveBeenCalled();
          expect(logSpy).toHaveBeenCalledWith('Unknown Call Event mobiusEvent: registration.down', {
            file: 'callManager',
            method: 'dequeueWsEvents'
          });
        case 2:
        case "end":
          return _context17.stop();
      }
    }, _callee17);
  })));
});
//# sourceMappingURL=callManager.test.js.map
