"use strict";

var _typeof = require("@babel/runtime-corejs2/helpers/typeof");
var _Reflect$construct = require("@babel/runtime-corejs2/core-js/reflect/construct");
var _Array$from = require("@babel/runtime-corejs2/core-js/array/from");
var _Symbol = require("@babel/runtime-corejs2/core-js/symbol");
var _Symbol$iterator = require("@babel/runtime-corejs2/core-js/symbol/iterator");
var _Array$isArray = require("@babel/runtime-corejs2/core-js/array/is-array");
var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
var _values = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/values"));
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 WebexCalling = _interopRequireWildcard(require("@webex/calling"));
var _events = _interopRequireDefault(require("events"));
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 _t3 in e) "default" !== _t3 && {}.hasOwnProperty.call(e, _t3) && ((i = (o = _Object$defineProperty) && _Object$getOwnPropertyDescriptor(e, _t3)) && (i.get || i.set) ? o(f, _t3, i) : f[_t3] = e[_t3]); return f; })(e, t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && r[_Symbol$iterator] || r["@@iterator"]; if (!t) { if (_Array$isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
/* eslint-disable require-jsdoc */
require('@webex/internal-plugin-device');
require('@webex/internal-plugin-mercury');
require('@webex/internal-plugin-encryption');
require('@webex/plugin-logger');
require('@webex/internal-plugin-support');
var merge = require('lodash/merge');
var WebexCore = require('@webex/webex-core').default;
var config = require('./config');
var Webex = WebexCore.extend({
  webex: true
});
var CALLING_FILE = 'Calling';
var logContext = {
  file: CALLING_FILE,
  method: 'calling.register'
};
var Calling = /*#__PURE__*/function (_EventEmitter) {
  function Calling(_ref) {
    var _this;
    var webex = _ref.webex,
      webexConfig = _ref.webexConfig,
      callingConfig = _ref.callingConfig;
    (0, _classCallCheck2.default)(this, Calling);
    _this = _callSuper(this, Calling);
    _this.callingConfig = callingConfig;
    _this.log = WebexCalling.Logger;
    _this.log.setLogger(callingConfig.logger.level, CALLING_FILE);
    _this.registered = false;
    if (webex) {
      _this.webex = webex;
      if (callingConfig.logger.level) {
        _this.webex.logger.config.level = callingConfig.logger.level; // override the webex logger level
      }
      _this.log.setWebexLogger(_this.webex.logger);
    } else {
      webexConfig.config = merge({}, config, webexConfig.config);
      _this.webex = new Webex(webexConfig);
      _this.webex.once('ready', function () {
        if (callingConfig.logger.level) {
          _this.webex.logger.config.level = callingConfig.logger.level; // override the webex logger level
        }
        _this.log.setWebexLogger(_this.webex.logger);
        _this.emit('ready');
        _this.log = _this.webex.logger;
      });
    }
    return _this;
  }
  (0, _inherits2.default)(Calling, _EventEmitter);
  return (0, _createClass2.default)(Calling, [{
    key: "register",
    value: function register() {
      var _this2 = this;
      return this.webex.internal.device.register().then(function () {
        _this2.log.info('Authentication: webex.internal.device.register successful', logContext);
        return _this2.webex.internal.mercury.connect().then(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
          var _t;
          return _regenerator.default.wrap(function (_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                _this2.log.info('Authentication: webex.internal.mercury.connect successful', logContext);
                _this2.registered = true;
                _context.prev = 1;
                _context.next = 2;
                return _this2.initializeClients();
              case 2:
                _context.next = 4;
                break;
              case 3:
                _context.prev = 3;
                _t = _context["catch"](1);
                _this2.log.warn("Error occurred while initializing clients ".concat(_t), logContext);
              case 4:
              case "end":
                return _context.stop();
            }
          }, _callee, null, [[1, 3]]);
        }))).catch(function (error) {
          _this2.log.warn("Error occurred during mercury.connect() ".concat(error), logContext);
        });
      }).catch(function (error) {
        _this2.log.warn("Error occurred during device.register() ".concat(error), logContext);
      });
    }
  }, {
    key: "deregister",
    value: function () {
      var _deregister = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
        var _this$callingClient,
          _this3 = this;
        var lines, _iterator, _step, line;
        return _regenerator.default.wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (this.registered) {
                _context2.next = 1;
                break;
              }
              this.log.info('Authentication: webex.internal.device.deregister already done', logContext);
              return _context2.abrupt("return", _promise.default.resolve());
            case 1:
              lines = (0, _values.default)((_this$callingClient = this.callingClient) === null || _this$callingClient === void 0 ? void 0 : _this$callingClient.getLines());
              _iterator = _createForOfIteratorHelper(lines);
              try {
                for (_iterator.s(); !(_step = _iterator.n()).done;) {
                  line = _step.value;
                  if (line.getStatus() === 'active') {
                    line.deregister(true); // Close Mobius WSS by passing true
                  }
                }
              } catch (err) {
                _iterator.e(err);
              } finally {
                _iterator.f();
              }
              return _context2.abrupt("return",
              // @ts-ignore
              this.webex.internal.mercury.disconnect().then(function () {
                _this3.log.info('Authentication: webex.internal.mercury.disconnect successful', logContext);

                // @ts-ignore
                return _this3.webex.internal.device.unregister();
              }).then(function () {
                _this3.log.info('Authentication: webex.internal.device.deregister successful', logContext);
                _this3.registered = false;
              }).catch(function (error) {
                _this3.log.warn("Error occurred during mercury.disconnect() or device.deregister() ".concat(error), logContext);
              }));
            case 2:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function deregister() {
        return _deregister.apply(this, arguments);
      }
      return deregister;
    }()
  }, {
    key: "initializeClients",
    value: function () {
      var _initializeClients = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
        var _this$callingConfig, clientConfig, callingClientConfig, logger, _t2;
        return _regenerator.default.wrap(function (_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              _this$callingConfig = this.callingConfig, clientConfig = _this$callingConfig.clientConfig, callingClientConfig = _this$callingConfig.callingClientConfig, logger = _this$callingConfig.logger;
              if (!clientConfig.calling) {
                _context3.next = 2;
                break;
              }
              _context3.next = 1;
              return WebexCalling.createClient(this.webex, callingClientConfig);
            case 1:
              _t2 = _context3.sent;
              _context3.next = 3;
              break;
            case 2:
              _t2 = undefined;
            case 3:
              this.callingClient = _t2;
              this.contactClient = clientConfig.contact ? WebexCalling.createContactsClient(this.webex, logger) : undefined;
              this.callHistoryClient = clientConfig.callHistory ? WebexCalling.createCallHistoryClient(this.webex, logger) : undefined;
              this.voicemailClient = clientConfig.voicemail ? WebexCalling.createVoicemailClient(this.webex, logger) : undefined;
              this.callSettingsClient = clientConfig.callSettings ? WebexCalling.createCallSettingsClient(this.webex, logger) : undefined;
            case 4:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function initializeClients() {
        return _initializeClients.apply(this, arguments);
      }
      return initializeClients;
    }()
  }], [{
    key: "createMicrophoneStream",
    get: function get() {
      return WebexCalling.createMicrophoneStream;
    }
  }, {
    key: "createNoiseReductionEffect",
    value: function createNoiseReductionEffect(options) {
      return new WebexCalling.NoiseReductionEffect(options);
    }
  }]);
}(_events.default);
var createCalling = /*#__PURE__*/function () {
  var _ref4 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4(_ref3) {
    var webex, webexConfig, callingConfig, callingInstance;
    return _regenerator.default.wrap(function (_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          webex = _ref3.webex, webexConfig = _ref3.webexConfig, callingConfig = _ref3.callingConfig;
          callingInstance = new Calling({
            webex: webex,
            webexConfig: webexConfig,
            callingConfig: callingConfig
          });
          if (!webex) {
            _context4.next = 1;
            break;
          }
          _context4.next = 1;
          return callingInstance.initializeClients();
        case 1:
          return _context4.abrupt("return", callingInstance);
        case 2:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  }));
  return function createCalling(_x) {
    return _ref4.apply(this, arguments);
  };
}();
Calling.init = /*#__PURE__*/function () {
  var _ref5 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee5(attrs) {
    var callingInstance;
    return _regenerator.default.wrap(function (_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          _context5.next = 1;
          return createCalling(attrs);
        case 1:
          callingInstance = _context5.sent;
          return _context5.abrupt("return", callingInstance);
        case 2:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  }));
  return function (_x2) {
    return _ref5.apply(this, arguments);
  };
}();
var _default = exports.default = Calling;
//# sourceMappingURL=calling.js.map
