"use strict";

var _typeof = require("@babel/runtime-corejs2/helpers/typeof");
var _Object$keys = 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 _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _asyncMutex = require("async-mutex");
var _testUtil = require("../../common/testUtil");
var _registerFixtures = require("../registration/registerFixtures");
var _common = require("../../common");
var _types = require("../../common/types");
var _types2 = require("./types");
var _ = _interopRequireDefault(require("."));
var utils = _interopRequireWildcard(require("../../common/Utils"));
var _SDKConnector = _interopRequireDefault(require("../../SDKConnector"));
var _constants = require("../constants");
var _types3 = require("../../Logger/types");
var regUtils = _interopRequireWildcard(require("../registration/register"));
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 _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); }
function ownKeys(e, r) { var t = _Object$keys(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; }
jest.mock('../../mobius-socket', function () {
  return {
    getMobiusSocketInstance: jest.fn().mockReturnValue({
      sendWssRequest: jest.fn()
    })
  };
});
jest.spyOn(utils, 'uploadLogs').mockResolvedValue(undefined);
describe('Line Tests', function () {
  var mutex = new _asyncMutex.Mutex();
  var webex = (0, _testUtil.getTestUtilsWebex)();
  _SDKConnector.default.setWebex(webex);
  beforeEach(function () {
    _request.APIRequest.resetInstance();
    _request.APIRequest.getInstance({
      webex: webex,
      isMobiusSocketEnabled: false
    });
  });
  var defaultServiceData = {
    indicator: _types.ServiceIndicator.CALLING,
    domain: ''
  };
  var createRegistrationSpy = jest.spyOn(regUtils, 'createRegistration');
  var mobiusUris = (0, _common.filterMobiusUris)((0, _testUtil.getMobiusDiscoveryResponse)(), _registerFixtures.URL);
  var primaryMobiusUris = jest.fn(function () {
    return mobiusUris.primary;
  });
  var backupMobiusUris = jest.fn(function () {
    return mobiusUris.backup;
  });
  var userId = webex.internal.device.userId;
  var clientDeviceUri = webex.internal.device.url;
  var mockJwe = 'mockJwe';
  var guestServiceData = {
    indicator: _types.ServiceIndicator.GUEST_CALLING,
    domain: '',
    guestName: 'testUser'
  };
  var handleErrorSpy = jest.spyOn(utils, 'handleRegistrationErrors');
  // Simulate node fetch by adding the mock webex.request
  global.fetch = webex.request;
  jest.clearAllMocks();
  describe('Line Registration tests', function () {
    var line;
    var mockRegistrationBody = (0, _testUtil.getMockDeviceInfo)();
    var discoveryBody = (0, _testUtil.getMobiusDiscoveryResponse)();
    var primaryUrl = "".concat(discoveryBody.primary.uris[0], "/calling/web/");
    var registrationPayload = {
      statusCode: 200,
      body: mockRegistrationBody
    };
    beforeEach(function () {
      line = new _.default(userId, clientDeviceUri, mutex, primaryMobiusUris(), backupMobiusUris(), _types3.LOGGER.INFO);
    });
    afterEach(function () {
      jest.clearAllTimers();
      jest.clearAllMocks();
      jest.useRealTimers();
      line.removeAllListeners();
    });
    it('verify successful Registration cases and keepalive', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
      return _regenerator.default.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            jest.useFakeTimers();
            webex.request.mockReturnValue(registrationPayload);
            expect(createRegistrationSpy).toBeCalledOnceWith(webex, defaultServiceData, expect.any(_asyncMutex.Mutex), expect.anything(), _types3.LOGGER.INFO, undefined);
            expect(line.getStatus()).toEqual(_types.RegistrationStatus.IDLE);
            _context.next = 1;
            return line.register();
          case 1:
            expect(webex.request).toBeCalledOnceWith(_objectSpread(_objectSpread({}, (0, _testUtil.getMockRequestTemplate)()), {}, {
              body: {
                userId: userId,
                clientDeviceUri: clientDeviceUri,
                serviceData: defaultServiceData
              },
              uri: "".concat(primaryUrl, "device"),
              method: 'POST'
            }));
            expect(handleErrorSpy).not.toBeCalled();
            expect(line.getStatus()).toEqual(_types.RegistrationStatus.ACTIVE);
            expect(line.getActiveMobiusUrl()).toEqual(primaryUrl);
            expect(line.getLoggingLevel()).toEqual(_types3.LOGGER.INFO);
            expect(line.getDeviceId()).toEqual(mockRegistrationBody.device.deviceId);
            expect(line.callManager.lineDict[mockRegistrationBody.device.deviceId]).toEqual(line);
            webex.request.mockClear();
            jest.advanceTimersByTime(30 * 1000);
            _context.next = 2;
            return _promise.default.resolve();
          case 2:
            jest.useRealTimers();
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    it('verify successful Registration cases and keepalive for a guest user', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
      var guestLine;
      return _regenerator.default.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            createRegistrationSpy.mockClear();
            guestLine = new _.default(userId, clientDeviceUri, mutex, primaryMobiusUris(), backupMobiusUris(), _types3.LOGGER.INFO, guestServiceData, mockJwe);
            jest.useFakeTimers();
            webex.request.mockReturnValue(registrationPayload);
            expect(createRegistrationSpy).toBeCalledOnceWith(webex, guestServiceData, expect.any(_asyncMutex.Mutex), expect.anything(), _types3.LOGGER.INFO, mockJwe);
            expect(guestLine.getStatus()).toEqual(_types.RegistrationStatus.IDLE);
            _context2.next = 1;
            return guestLine.register();
          case 1:
            expect(webex.request).toBeCalledOnceWith(_objectSpread(_objectSpread({}, (0, _testUtil.getMockRequestTemplate)()), {}, {
              body: {
                userId: userId,
                clientDeviceUri: clientDeviceUri,
                serviceData: _objectSpread(_objectSpread({}, guestServiceData), {}, {
                  jwe: mockJwe
                })
              },
              uri: "".concat(primaryUrl, "device"),
              method: 'POST'
            }));
            expect(handleErrorSpy).not.toBeCalled();
            expect(guestLine.getStatus()).toEqual(_types.RegistrationStatus.ACTIVE);
            expect(guestLine.getActiveMobiusUrl()).toEqual(primaryUrl);
            expect(guestLine.getLoggingLevel()).toEqual(_types3.LOGGER.INFO);
            expect(guestLine.getDeviceId()).toEqual(mockRegistrationBody.device.deviceId);
            webex.request.mockClear();
            jest.advanceTimersByTime(30 * 1000);
            _context2.next = 2;
            return _promise.default.resolve();
          case 2:
            jest.useRealTimers();
          case 3:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    })));
    it('verify failure Registration cases all requests fail ', /*#__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:
            line.removeAllListeners(_types2.LINE_EVENTS.ERROR);
            webex.request.mockRejectedValue({
              statusCode: 401
            });
            line.on(_types2.LINE_EVENTS.ERROR, function (error) {
              expect(error.message).toBe('User is unauthorized due to an expired token. Sign out, then sign back in.');
            });
            expect(line.getStatus()).toBe(_types.RegistrationStatus.IDLE);
            line.register();
            _context3.next = 1;
            return utils.waitForMsecs(20);
          case 1:
            expect(line.getStatus()).toBe(_types.RegistrationStatus.INACTIVE);
            expect(handleErrorSpy).toBeCalledOnceWith(expect.anything(), expect.anything(), {
              file: _constants.REGISTRATION_FILE,
              method: 'triggerRegistration'
            }, expect.anything(), expect.anything(), expect.any(Number));
          case 2:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    it('verify successful de-registration cases', /*#__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:
            webex.request.mockReturnValueOnce(registrationPayload);
            expect(line.getStatus()).toEqual(_types.RegistrationStatus.IDLE);
            _context4.next = 1;
            return line.register();
          case 1:
            expect(line.getStatus()).toEqual(_types.RegistrationStatus.ACTIVE);
            _context4.next = 2;
            return line.deregister();
          case 2:
            expect(line.getStatus()).toEqual(_types.RegistrationStatus.IDLE);
          case 3:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    })));
  });
  describe('Line calling tests', function () {
    var line;
    beforeEach(function () {
      line = new _.default(userId, clientDeviceUri, mutex, primaryMobiusUris(), backupMobiusUris(), _types3.LOGGER.INFO);
    });
    afterEach(function () {
      jest.clearAllTimers();
      jest.clearAllMocks();
      jest.useRealTimers();
      line.removeAllListeners();
    });
    it('Return a successful call object while making call', function () {
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      var call = line.makeCall({
        address: '5003',
        type: _types.CallType.URI
      });
      expect(createCallSpy).toBeCalledOnceWith(_types.CallDirection.OUTBOUND, undefined, line.lineId, {
        address: 'tel:5003',
        type: 'uri'
      });
      expect(call).toBeTruthy();
      expect(line.getCall(call ? call.getCorrelationId() : '')).toBe(call);
      expect(call ? call.direction : undefined).toStrictEqual(_types.CallDirection.OUTBOUND);
      call === null || call === void 0 ? void 0 : call.end();
    });
    it('Return a successful call object while making call to FAC codes', function () {
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      var call = line.makeCall({
        address: '*25',
        type: _types.CallType.URI
      });
      expect(createCallSpy).toBeCalledOnceWith(_types.CallDirection.OUTBOUND, undefined, line.lineId, {
        address: 'tel:*25',
        type: 'uri'
      });
      expect(call).toBeTruthy();
      expect(call ? call.direction : undefined).toStrictEqual(_types.CallDirection.OUTBOUND);
      call === null || call === void 0 ? void 0 : call.end();
    });
    it('Remove spaces from dialled number while making call', function () {
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      var call = line.makeCall({
        address: '+91 123 456 7890',
        type: _types.CallType.URI
      });
      expect(createCallSpy).toBeCalledOnceWith(_types.CallDirection.OUTBOUND, undefined, line.lineId, {
        address: 'tel:+911234567890',
        type: 'uri'
      });
      expect(call).toBeTruthy();
      expect(call ? call.direction : undefined).toStrictEqual(_types.CallDirection.OUTBOUND);
      expect(call ? call.destination.address : undefined).toStrictEqual('tel:+911234567890');
      call === null || call === void 0 ? void 0 : call.end();
    });
    it('Remove hyphen from dialled number while making call', function () {
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      var call = line.makeCall({
        address: '123-456-7890',
        type: _types.CallType.URI
      });
      expect(createCallSpy).toBeCalledOnceWith(_types.CallDirection.OUTBOUND, undefined, line.lineId, {
        address: 'tel:1234567890',
        type: 'uri'
      });
      expect(call).toBeTruthy();
      expect(call ? call.direction : undefined).toStrictEqual(_types.CallDirection.OUTBOUND);
      expect(call ? call.destination.address : undefined).toStrictEqual('tel:1234567890');
      call === null || call === void 0 ? void 0 : call.end();
    });
    it('attempt to create call with incorrect number format 1', function (done) {
      // There may be other listeners , which may create race
      line.removeAllListeners(_types2.LINE_EVENTS.ERROR);
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      line.on(_types2.LINE_EVENTS.ERROR, function (error) {
        expect(error.message).toBe('An invalid phone number was detected. Check the number and try again.');
        done();
      });
      try {
        var call = line.makeCall({
          address: 'select#$@^^',
          type: _types.CallType.URI
        });
        expect(call).toBeUndefined();
        expect(createCallSpy).not.toBeCalledOnceWith({});
      } catch (error) {
        done(error);
      }
    });
    it('attempt to create call with incorrect number format 2', function (done) {
      expect.assertions(4);
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');
      line.on(_types2.LINE_EVENTS.ERROR, function (error) {
        expect(error.message).toBe('An invalid phone number was detected. Check the number and try again.');
        done();
      });
      try {
        var call = line.makeCall({
          address: '+1@8883332505',
          type: _types.CallType.URI
        });
        expect(call).toBeUndefined();
        expect(createCallSpy).not.toBeCalledOnceWith({});
      } catch (error) {
        done(error);
      }
    });
    it('attempt to create call with guest calling service indicator', function () {
      expect.assertions(2);
      var createCallSpy = jest.spyOn(line.callManager, 'createCall');

      // Mocking the serviceData to have GUEST_CALLING indicator
      line = new _.default(userId, clientDeviceUri, mutex, primaryMobiusUris(), backupMobiusUris(), _types3.LOGGER.INFO, {
        indicator: _types.ServiceIndicator.GUEST_CALLING
      });
      var call = line.makeCall();
      expect(call).toBeTruthy();
      expect(createCallSpy).toBeCalledWith(_types.CallDirection.OUTBOUND, undefined, expect.any(String));
    });
  });
});
//# sourceMappingURL=line.test.js.map
