"use strict";

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 _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
exports.setup = setup;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var _recompose = require("recompose");
var _reactRedux = require("react-redux");
var _redux = require("redux");
var _reduxModuleAvatar = require("@webex/redux-module-avatar");
var _reduxModuleConversation = require("@webex/redux-module-conversation");
var _reduxModuleErrors = require("@webex/redux-module-errors");
var _reduxModuleMercury = require("@webex/redux-module-mercury");
var _reduxModuleSpaces = require("@webex/redux-module-spaces");
var _reduxModuleUsers = require("@webex/redux-module-users");
var _reactComponentUtils = require("@webex/react-component-utils");
var _actions = require("../actions");
var _selector = require("../selector");
var _constants = require("../constants");
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; }
function setup(props) {
  var prevProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var conversation = props.conversation,
    destination = props.destination,
    errors = props.errors,
    sparkInstance = props.sparkInstance,
    sparkState = props.sparkState,
    spaceDetails = props.spaceDetails,
    widgetStatus = props.widgetStatus,
    mercuryStatus = props.mercuryStatus,
    users = props.users,
    spaces = props.spaces;
  if (sparkInstance && sparkState.authenticated && sparkState.registered && !sparkState.hasError) {
    // Check if we need to reload space
    if (widgetStatus.shouldReloadWidget && prevProps && !prevProps.widgetStatus.shouldReloadWidget) {
      props.resetConversation();
      props.reloadWidget();
      props.resetErrors();
    }

    // Check for destination Change
    if (destination && prevProps.destination) {
      var previousDestination = prevProps.destination;
      if (destination.id !== previousDestination.id || destination.type !== previousDestination.type) {
        sparkInstance.logger.info('Destination has changed, widget reloading...');
        props.updateWidgetStatus({
          shouldReloadWidget: true
        });
      }
    }

    // Connect to websocket (mercury)
    if (!mercuryStatus.hasConnected && !mercuryStatus.connecting && !mercuryStatus.connected && sparkState.registered) {
      props.connectToMercury(sparkInstance);
    }

    // Get space details for given destination
    // Get space details for given destination
    if (!widgetStatus.isFetchingSpaceDetails && !errors.get('hasError') && !spaceDetails) {
      // If the selector isn't returning a destination object and we have props for them, store
      if (destination) {
        // Use destination object from store to fetch space details
        props.getSpaceDetails({
          sparkInstance: sparkInstance,
          destinationId: destination.id,
          destinationType: destination.type,
          intl: props.intl
        });
        // Fetch 1:1 User details
        if (destination.type === _constants.destinationTypes.EMAIL && !users.getIn(['byEmail', destination.id])) {
          props.getUser({
            email: destination.id
          }, sparkInstance);
        }
        if (destination.type === _constants.destinationTypes.USERID && !users.getIn(['byId', destination.id])) {
          props.getUser({
            id: destination.id
          }, sparkInstance);
        }
        if (destination.type === _constants.destinationTypes.SPACEID && !spaces.getIn(['byId', (0, _reactComponentUtils.validateAndDecodeId)(destination.id).id])) {
          props.fetchSpace(sparkInstance, (0, _reactComponentUtils.validateAndDecodeId)(destination.id));
        }
      } else {
        // Destination has not been stored yet, process and store.
        var destinationId = props.destinationId,
          destinationType = props.destinationType;
        var cluster;
        var id = destinationId;
        if (destinationType === _constants.destinationTypes.EMAIL && destinationId) {
          id = destinationId.toLowerCase();
        } else if (destinationType === _constants.destinationTypes.SPACEID && destinationId) {
          var _deconstructHydraId = (0, _reactComponentUtils.deconstructHydraId)(destinationId);
          cluster = _deconstructHydraId.cluster;
        }
        props.storeDestination(_objectSpread({
          id: id,
          type: destinationType
        }, cluster && {
          cluster: cluster
        }));
      }
    }
    if (conversation.get('id')) {
      props.fetchAvatar({
        space: conversation.toJS()
      }, sparkInstance);
    }
  }
}
var _default = exports.default = (0, _recompose.compose)((0, _reactRedux.connect)(_selector.getSpaceWidgetProps, function (dispatch) {
  return (0, _redux.bindActionCreators)({
    connectToMercury: _reduxModuleMercury.connectToMercury,
    fetchSpace: _reduxModuleSpaces.fetchSpace,
    getUser: _reduxModuleUsers.getUser,
    getSpaceDetails: _actions.getSpaceDetails,
    reloadWidget: _actions.reloadWidget,
    resetConversation: _reduxModuleConversation.resetConversation,
    resetErrors: _reduxModuleErrors.resetErrors,
    storeDestination: _actions.storeDestination,
    updateWidgetStatus: _actions.updateWidgetStatus,
    fetchAvatar: _reduxModuleAvatar.fetchAvatar
  }, dispatch);
}), (0, _recompose.lifecycle)({
  componentWillMount: function componentWillMount() {
    setup(this.props);
  },
  shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
    return nextProps !== this.props;
  },
  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
    setup(nextProps, this.props);
  }
}));