"use strict";

var _Reflect$construct = require("@babel/runtime-corejs2/core-js/reflect/construct");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _weakMap = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/weak-map"));
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var _uuid = require("uuid");
var _constants = require("../../common/constants");
var _types = require("../../common/types");
var _types2 = require("./types");
var _constants2 = require("../constants");
var _Logger = _interopRequireDefault(require("../../Logger"));
var _registration = require("../registration");
var _impl = require("../../Events/impl");
var _LineError = require("../../Errors/catalog/LineError");
var _common = require("../../common");
var _SDKConnector = _interopRequireDefault(require("../../SDKConnector"));
var _types3 = require("../../Events/types");
var _callManager = require("../calling/callManager");
var _types4 = require("../../Errors/types");
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
var _webex = /*#__PURE__*/new _weakMap.default();
var _mutex = /*#__PURE__*/new _weakMap.default();
var _sdkConnector = /*#__PURE__*/new _weakMap.default();
var _primaryMobiusUris = /*#__PURE__*/new _weakMap.default();
var _backupMobiusUris = /*#__PURE__*/new _weakMap.default();
var Line = exports.default = /*#__PURE__*/function (_Eventing) {
  function Line(userId, clientDeviceUri, mutex, primaryMobiusUris, backupMobiusUris, logLevel, serviceDataConfig, jwe, phoneNumber, extension, voicemail) {
    var _this;
    (0, _classCallCheck2.default)(this, Line);
    _this = _callSuper(this, Line);
    _classPrivateFieldInitSpec(_this, _webex, void 0);
    _classPrivateFieldInitSpec(_this, _mutex, void 0);
    _classPrivateFieldInitSpec(_this, _sdkConnector, void 0);
    (0, _defineProperty2.default)(_this, "registration", void 0);
    (0, _defineProperty2.default)(_this, "userId", void 0);
    (0, _defineProperty2.default)(_this, "clientDeviceUri", void 0);
    (0, _defineProperty2.default)(_this, "lineId", void 0);
    (0, _defineProperty2.default)(_this, "mobiusDeviceId", void 0);
    (0, _defineProperty2.default)(_this, "mobiusUri", void 0);
    (0, _defineProperty2.default)(_this, "phoneNumber", void 0);
    (0, _defineProperty2.default)(_this, "extension", void 0);
    (0, _defineProperty2.default)(_this, "sipAddresses", []);
    (0, _defineProperty2.default)(_this, "voicemail", void 0);
    (0, _defineProperty2.default)(_this, "lastSeen", void 0);
    (0, _defineProperty2.default)(_this, "keepaliveInterval", void 0);
    (0, _defineProperty2.default)(_this, "callKeepaliveInterval", void 0);
    (0, _defineProperty2.default)(_this, "rehomingIntervalMin", void 0);
    (0, _defineProperty2.default)(_this, "rehomingIntervalMax", void 0);
    (0, _defineProperty2.default)(_this, "voicePortalNumber", void 0);
    (0, _defineProperty2.default)(_this, "voicePortalExtension", void 0);
    (0, _defineProperty2.default)(_this, "callManager", void 0);
    (0, _defineProperty2.default)(_this, "serviceData", void 0);
    _classPrivateFieldInitSpec(_this, _primaryMobiusUris, void 0);
    _classPrivateFieldInitSpec(_this, _backupMobiusUris, void 0);
    /**
     * Line events emitter
     */
    (0, _defineProperty2.default)(_this, "lineEmitter", function (event, deviceInfo, lineError) {
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.LINE_FILE,
        method: _constants2.METHODS.LINE_EMITTER
      });
      switch (event) {
        case _types2.LINE_EVENTS.REGISTERED:
          if (deviceInfo) {
            _this.normalizeLine(deviceInfo);
            _this.emit(event, _this);
          }
          break;
        case _types2.LINE_EVENTS.UNREGISTERED:
        case _types2.LINE_EVENTS.RECONNECTED:
        case _types2.LINE_EVENTS.RECONNECTING:
          _this.emit(event);
          break;
        case _types2.LINE_EVENTS.ERROR:
          if (lineError) {
            _this.emit(event, lineError);
          }
          break;
        default:
          break;
      }
    });
    /**
     * Gets registration status
     */
    (0, _defineProperty2.default)(_this, "getStatus", function () {
      return _this.registration.getStatus();
    });
    /**
     * Gets device id
     */
    (0, _defineProperty2.default)(_this, "getDeviceId", function () {
      var _this$registration$ge;
      return (_this$registration$ge = _this.registration.getDeviceInfo().device) === null || _this$registration$ge === void 0 ? void 0 : _this$registration$ge.deviceId;
    });
    /**
     * Initiates a call to the specified destination.
     * @param dest - The call details including destination information.
     */
    (0, _defineProperty2.default)(_this, "makeCall", function (dest) {
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.LINE_FILE,
        method: _constants2.METHODS.MAKE_CALL
      });
      var call;
      if (dest) {
        var match = dest.address.match(_constants2.VALID_PHONE_REGEX);
        if (match && match[0].length === dest.address.length) {
          var _this$registration$ge2, _call;
          var sanitizedNumber = dest.address.replace(/[^[*+]\d#]/gi, '').replace(/\s+/gi, '').replace(/-/gi, '');
          var formattedDest = {
            type: dest.type,
            address: "tel:".concat(sanitizedNumber)
          };
          call = _this.callManager.createCall(_types.CallDirection.OUTBOUND, (_this$registration$ge2 = _this.registration.getDeviceInfo().device) === null || _this$registration$ge2 === void 0 ? void 0 : _this$registration$ge2.deviceId, _this.lineId, formattedDest);
          _Logger.default.log("New call created, callId: ".concat((_call = call) === null || _call === void 0 ? void 0 : _call.getCallId()), {
            file: _constants2.LINE_FILE,
            method: _constants2.METHODS.MAKE_CALL
          });
        } else {
          _Logger.default.warn('Invalid phone number detected', {
            file: _constants2.LINE_FILE,
            method: _constants2.METHODS.MAKE_CALL
          });
          var err = new _LineError.LineError('An invalid phone number was detected. Check the number and try again.', {}, _types4.ERROR_TYPE.CALL_ERROR, _types.RegistrationStatus.ACTIVE);
          _this.emit(_types2.LINE_EVENTS.ERROR, err);
        }
        return call;
      }
      if (_this.serviceData.indicator === _types.ServiceIndicator.GUEST_CALLING) {
        var _this$registration$ge3;
        call = _this.callManager.createCall(_types.CallDirection.OUTBOUND, (_this$registration$ge3 = _this.registration.getDeviceInfo().device) === null || _this$registration$ge3 === void 0 ? void 0 : _this$registration$ge3.deviceId, _this.lineId);
        _Logger.default.info("New guest call created, callId: ".concat(call.getCallId()), {
          file: _constants2.LINE_FILE,
          method: _constants2.METHODS.MAKE_CALL
        });
        return call;
      }
      return undefined;
    });
    /**
     * @param callId -.
     * @param correlationId -.
     */
    (0, _defineProperty2.default)(_this, "getCall", function (correlationId) {
      return _this.callManager.getCall(correlationId);
    });
    _this.lineId = (0, _uuid.v4)();
    _this.userId = userId;
    _this.clientDeviceUri = clientDeviceUri;
    _this.phoneNumber = phoneNumber;
    _this.extension = extension;
    _this.voicemail = voicemail;
    _classPrivateFieldSet(_sdkConnector, _this, _SDKConnector.default);
    _classPrivateFieldSet(_webex, _this, _classPrivateFieldGet(_sdkConnector, _this).getWebex());
    _classPrivateFieldSet(_mutex, _this, mutex);
    _classPrivateFieldSet(_primaryMobiusUris, _this, primaryMobiusUris);
    _classPrivateFieldSet(_backupMobiusUris, _this, backupMobiusUris);
    _this.serviceData = serviceDataConfig !== null && serviceDataConfig !== void 0 && serviceDataConfig.indicator ? serviceDataConfig : {
      indicator: _types.ServiceIndicator.CALLING,
      domain: ''
    };
    (0, _common.validateServiceData)(_this.serviceData);
    _this.registration = (0, _registration.createRegistration)(_classPrivateFieldGet(_webex, _this), _this.serviceData, _classPrivateFieldGet(_mutex, _this), _this.lineEmitter, logLevel, jwe);
    _Logger.default.setLogger(logLevel, _constants2.LINE_FILE);
    _this.callManager = (0, _callManager.getCallManager)(_classPrivateFieldGet(_webex, _this), _this.serviceData.indicator);
    _this.incomingCallListener();
    return _this;
  }

  /**
   * Wrapper to for device registration.
   */
  (0, _inherits2.default)(Line, _Eventing);
  return (0, _createClass2.default)(Line, [{
    key: "register",
    value: (function () {
      var _register = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
        var _this2 = this;
        return _regenerator.default.wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.LINE_FILE,
                method: _constants2.METHODS.REGISTER
              });
              _context2.next = 1;
              return _classPrivateFieldGet(_mutex, this).runExclusive(/*#__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:
                      _this2.emit(_types2.LINE_EVENTS.CONNECTING);
                      _this2.registration.setMobiusServers(_classPrivateFieldGet(_primaryMobiusUris, _this2), _classPrivateFieldGet(_backupMobiusUris, _this2));
                      _context.next = 1;
                      return _this2.registration.triggerRegistration();
                    case 1:
                    case "end":
                      return _context.stop();
                  }
                }, _callee);
              })));
            case 1:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function register() {
        return _register.apply(this, arguments);
      }
      return register;
    }()
    /**
     * Wrapper to for device  deregister.
     */
    )
  }, {
    key: "deregister",
    value: (function () {
      var _deregister = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
        var closeMobiusWss,
          _args3 = arguments;
        return _regenerator.default.wrap(function (_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              closeMobiusWss = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : false;
              _Logger.default.info(_constants.METHOD_START_MESSAGE, {
                file: _constants2.LINE_FILE,
                method: _constants2.METHODS.DEREGISTER
              });
              _context3.next = 1;
              return this.registration.deregister(closeMobiusWss);
            case 1:
              this.registration.setStatus(_types.RegistrationStatus.IDLE);
            case 2:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function deregister() {
        return _deregister.apply(this, arguments);
      }
      return deregister;
    }()
    /**
     * To normalize line class with Mobius response
     */
    )
  }, {
    key: "normalizeLine",
    value: function normalizeLine(deviceInfo) {
      var _device$addresses;
      var device = deviceInfo.device,
        keepaliveInterval = deviceInfo.keepaliveInterval,
        callKeepaliveInterval = deviceInfo.callKeepaliveInterval,
        rehomingIntervalMin = deviceInfo.rehomingIntervalMin,
        rehomingIntervalMax = deviceInfo.rehomingIntervalMax,
        voicePortalNumber = deviceInfo.voicePortalNumber,
        voicePortalExtension = deviceInfo.voicePortalExtension;
      this.mobiusDeviceId = device === null || device === void 0 ? void 0 : device.deviceId;
      this.mobiusUri = device === null || device === void 0 ? void 0 : device.uri;
      this.lastSeen = device === null || device === void 0 ? void 0 : device.lastSeen;
      this.sipAddresses = (_device$addresses = device === null || device === void 0 ? void 0 : device.addresses) !== null && _device$addresses !== void 0 ? _device$addresses : [];
      this.keepaliveInterval = keepaliveInterval;
      this.callKeepaliveInterval = callKeepaliveInterval;
      this.rehomingIntervalMin = rehomingIntervalMin;
      this.rehomingIntervalMax = rehomingIntervalMax;
      this.voicePortalNumber = voicePortalNumber;
      this.voicePortalExtension = voicePortalExtension;
      if (this.mobiusDeviceId) {
        this.callManager.updateLine(this.mobiusDeviceId, this);
      }
    }
  }, {
    key: "getLoggingLevel",
    value:
    /**
     * To get the current log Level.
     */
    function getLoggingLevel() {
      return _Logger.default.getLogLevel();
    }

    /**
     *  To get active url of Mobius.
     */
  }, {
    key: "getActiveMobiusUrl",
    value: function getActiveMobiusUrl() {
      return this.registration.getActiveMobiusUrl();
    }
  }, {
    key: "incomingCallListener",
    value:
    /**
     * An Incoming Call listener.
     */
    function incomingCallListener() {
      var _this3 = this;
      _Logger.default.info(_constants.METHOD_START_MESSAGE, {
        file: _constants2.LINE_FILE,
        method: _constants2.METHODS.INCOMING_CALL_LISTENER
      });
      _Logger.default.info('Listening for incoming calls... ', {
        file: _constants2.LINE_FILE,
        method: _constants2.METHODS.INCOMING_CALL_LISTENER
      });
      this.callManager.on(_types3.LINE_EVENT_KEYS.INCOMING_CALL, function (callObj) {
        _this3.emit(_types2.LINE_EVENTS.INCOMING_CALL, callObj);
      });
    }
  }]);
}(_impl.Eventing);
//# sourceMappingURL=index.js.map
