"use strict";

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.getSubmitOptions = exports.getSpaceWidgetProps = exports.getSpaceDetails = exports.getCurrentActivity = exports.getCall = exports.getActivityTypes = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/typeof"));
var _reselect = require("reselect");
var _reactComponentUtils = require("@webex/react-component-utils");
var _constants = require("./constants");
var getWidget = function getWidget(state) {
  return state.widgetSpace;
};
var getSpark = function getSpark(state) {
  return state.spark;
};
var getMedia = function getMedia(state) {
  return state.media;
};
var getConversation = function getConversation(state) {
  return state.conversation;
};
var getFeatures = function getFeatures(state) {
  return state.features;
};
var getUsers = function getUsers(state) {
  return state.users;
};
var getSpaces = function getSpaces(state) {
  return state.spaces;
};
var getOwnProps = function getOwnProps(state, ownProps) {
  return ownProps;
};
var getMercuryStatus = function getMercuryStatus(state) {
  return state.mercury.get('status');
};
var getCall = exports.getCall = (0, _reselect.createSelector)([getConversation, getMedia, getWidget, getOwnProps], function (conversation, media, widget, ownProps) {
  if (ownProps && ownProps.call && (0, _typeof2.default)(ownProps.call) === 'object' && ownProps.call.id) {
    return ownProps.call;
  }
  var mediaId;

  // Conversation is the easiest way to get a media id
  if (conversation.has('locusUrl')) {
    mediaId = media.getIn(['byLocusUrl', conversation.get('locusUrl')]);
  } else {
    var destination = widget.get('destination');
    if (!destination) {
      return null;
    }
    mediaId = media.getIn(['byDestination', destination.id]);

    // Incoming call
    if (!mediaId && [_constants.destinationTypes.SIP, _constants.destinationTypes.PSTN].includes(destination.type)) {
      // This is a bit of a hack. We're matching on the string, but this can
      // cause ambiguity if the phone numbers are too close.
      var matchedCall = media.get('byId').find(function (call) {
        if (call && call.has('instance')) {
          var _call$get = call.get('instance'),
            locus = _call$get.locus;
          if (locus && locus.host) {
            if (destination.type === _constants.destinationTypes.PSTN && locus.host.phoneNumber) {
              if (destination.id.startsWith('+')) {
                return locus.host.phoneNumber === destination.id;
              }
              return locus.host.phoneNumber.includes(destination.id);
            }
            if (locus.info && locus.info.sipUri) {
              return locus.info.sipUri.includes(destination.id);
            }
          }
        }
        return false;
      });
      if (matchedCall) {
        mediaId = media.getIn(['byLocusUrl', matchedCall.get('instance').locusUrl]);
      }
    }
  }
  var call = media.getIn(['byId', mediaId]);
  if (call && call.isDismissed) {
    return null;
  }
  return call;
});
var getCurrentActivity = exports.getCurrentActivity = (0, _reselect.createSelector)([getWidget, getFeatures, getOwnProps], function (widget) {
  if (widget.get('secondaryActivityType')) return widget.get('secondaryActivityType');
  return widget.get('primaryActivityType');
});

/**
 * Builds a space details object from store + calculated title & avatarid
 */
var getSpaceDetails = exports.getSpaceDetails = (0, _reselect.createSelector)([getWidget, getUsers, getSpaces, getCall], function (widget, users, spaces, call) {
  if (!widget.get('spaceDetails')) {
    return null;
  }
  var spaceDetails = widget.get('spaceDetails').toJS();
  var destination = widget.get('destination');
  if (!destination) {
    return spaceDetails;
  }
  var id = destination.id,
    type = destination.type;
  var avatarId, displayName;
  switch (type) {
    case _constants.destinationTypes.SIP:
    case _constants.destinationTypes.PSTN:
      {
        var _call$locusInfo, _call$locusInfo$self;
        if (call !== null && call !== void 0 && (_call$locusInfo = call.locusInfo) !== null && _call$locusInfo !== void 0 && (_call$locusInfo$self = _call$locusInfo.self) !== null && _call$locusInfo$self !== void 0 && _call$locusInfo$self.displayInfo) {
          displayName = call.locusInfo.self.displayInfo.primaryDisplayName;
        } else {
          displayName = id;
        }
        break;
      }
    case _constants.destinationTypes.EMAIL:
      {
        avatarId = users.getIn(['byEmail', id]);
        displayName = users.getIn(['byId', avatarId, 'displayName']);
        break;
      }
    case _constants.destinationTypes.USERID:
      {
        var _validateAndDecodeId = (0, _reactComponentUtils.validateAndDecodeId)(id),
          userId = _validateAndDecodeId.id;
        displayName = users.getIn(['byId', userId, 'displayName']);
        avatarId = userId;
        break;
      }
    case _constants.destinationTypes.SPACEID:
      if (spaceDetails.type === 'direct') {
        var currentUserId = users.get('currentUserId');
        var toUser = users.get('byId').find(function (u) {
          return u.get('id') !== currentUserId;
        });
        displayName = spaceDetails.title;
        if (toUser) {
          avatarId = toUser.get('id');
        }
      } else {
        var _validateAndDecodeId2 = (0, _reactComponentUtils.validateAndDecodeId)(id),
          tempId = _validateAndDecodeId2.id;
        displayName = spaces.getIn(['byId', tempId, 'displayName']);
        avatarId = tempId;
      }
      break;
    default:
      displayName = null;
  }
  spaceDetails.avatarId = avatarId;
  spaceDetails.title = displayName;
  return spaceDetails;
});
var getActivityTypes = exports.getActivityTypes = (0, _reselect.createSelector)([getWidget, getFeatures, getOwnProps], function (widget, features, ownProps) {
  var spaceActivities = ownProps.spaceActivities,
    call = ownProps.call;
  var destination = widget.get('destination');
  var spaceType = widget.getIn(['spaceDetails', 'type']);
  var filteredActivityTypes = [];
  var activityTypes = widget.get('activityTypes').toJS();
  if (spaceActivities) {
    activityTypes = activityTypes.filter(function (a) {
      return spaceActivities[a.name] !== false;
    });
  }
  activityTypes.forEach(function (activityType) {
    var isValid = true;

    // Filter activity Type based on spaceType
    if (spaceType && !activityType.spaceTypes.includes(spaceType)) {
      isValid = false;
    }
    // Filter activity type based on feature requirement
    if (activityType.feature && !activityType.feature.hide && !features.getIn(['items', activityType.feature.key])) {
      isValid = false;
    }
    // Hide flag on feature means to hide activity if feature is enabled
    if (activityType.feature && activityType.feature.hide && features.getIn(['items', activityType.feature.key])) {
      isValid = false;
    }
    // Filter based on destination type
    if (destination && destination.type && ([_constants.destinationTypes.SIP, _constants.destinationTypes.PSTN].includes(destination.type) || call) && ['message', 'files'].includes(activityType.name)) {
      isValid = false;
    }
    if (isValid) {
      filteredActivityTypes.push(activityType);
    }
  });
  return filteredActivityTypes;
});
var getSubmitOptions = exports.getSubmitOptions = (0, _reselect.createSelector)([getOwnProps], function (ownProps) {
  var _ownProps$showSubmitB = ownProps.showSubmitButton,
    showSubmitButton = _ownProps$showSubmitB === void 0 ? false : _ownProps$showSubmitB,
    _ownProps$sendMessage = ownProps.sendMessageOnReturnKey,
    sendMessageOnReturnKey = _ownProps$sendMessage === void 0 ? true : _ownProps$sendMessage;
  return {
    showSubmitButton: showSubmitButton,
    sendMessageOnReturnKey: sendMessageOnReturnKey
  };
});
var getSpaceWidgetProps = exports.getSpaceWidgetProps = (0, _reselect.createSelector)([getWidget, getSpark, getMedia, getSpaceDetails, getActivityTypes, getCall, getMercuryStatus, getCurrentActivity, getSubmitOptions], function (widget, spark, media, spaceDetails, activityTypes, call, mercuryStatus, currentActivity, _ref) {
  var showSubmitButton = _ref.showSubmitButton,
    sendMessageOnReturnKey = _ref.sendMessageOnReturnKey;
  return {
    activityTypes: activityTypes,
    destination: widget.get('destination'),
    media: media,
    mercuryStatus: mercuryStatus.toJS(),
    sparkInstance: spark.get('spark'),
    sparkState: spark.get('status'),
    spaceDetails: spaceDetails,
    widgetStatus: widget.get('status'),
    call: call,
    currentActivity: currentActivity,
    showSubmitButton: showSubmitButton,
    sendMessageOnReturnKey: sendMessageOnReturnKey
  };
});