"use strict";

exports.__esModule = true;
exports.default = ContributionActionsMenu;

var _react = _interopRequireWildcard(require("react"));

var _styles = require("@mui/material/styles");

var _reactIntl = require("react-intl");

var _Popper = _interopRequireDefault(require("@mui/material/Popper"));

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

var _CentralProgress = _interopRequireDefault(require("../CentralProgress"));

var _Errors = require("../../constants/Errors");

var _string = require("../../utils/string");

var _notistack = require("notistack");

var _contribution = require("../../utils/contribution");

var _classnames = _interopRequireDefault(require("classnames"));

var _ConfirmDialog = _interopRequireDefault(require("../ConfirmDialog/ConfirmDialog"));

var _lodash = require("lodash");

var _material = require("@mui/material");

var _Flagging = require("../../constants/Flagging");

var _core = require("@selfcommunity/core");

var _ContributionsActionsMenu = require("../../constants/ContributionsActionsMenu");

const _excluded = ["className", "feedObjectId", "feedObject", "feedObjectType", "commentObjectId", "commentObject", "onEditContribution", "onHideContribution", "onDeleteContribution", "onRestoreContribution", "onSuspendNotificationContribution", "PopperProps"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const PREFIX = 'SCContributionActionsMenu';
const classes = {
  root: `${PREFIX}-root`,
  button: `${PREFIX}-button`,
  popper: `${PREFIX}-popper`,
  paper: `${PREFIX}-paper`,
  item: `${PREFIX}-item`,
  itemText: `${PREFIX}-item-text`,
  subItem: `${PREFIX}-sub-item`,
  subItemText: `${PREFIX}-sub-item-text`,
  footerSubItems: `${PREFIX}-footer-sub-items`,
  selectedIcon: `${PREFIX}-selected-icon`,
  sectionBadge: `${PREFIX}-section-badge`,
  sectionWithSelectionIcon: `${PREFIX}-section-with-selection-icon`,
  visibilityBadge: `${PREFIX}-visibility-badge`
};
const PopperRoot = (0, _styles.styled)(_Popper.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  zIndex: 2,
  [`&.${classes.popper}`]: {
    overflow: 'visible',
    filter: 'drop-shadow(0px -1px 5px rgba(0,0,0,0.10))',
    mt: 1.5
  },
  [`& .${classes.paper}`]: {
    width: 280
  },
  [`& .${classes.footerSubItems}`]: {
    margin: '10px 10px 10px 17px',
    border: '1px solid #dddddd',
    padding: 5,
    borderRadius: 3,
    fontSize: 11
  },
  [`& .${classes.selectedIcon}`]: {
    marginLeft: 2,
    '&.MuiListItemIcon-root': {
      width: '10px'
    },
    '& svg': {
      fontSize: '1.4rem'
    }
  },
  [`& .${classes.sectionBadge}`]: {
    padding: 0,
    minWidth: 15,
    height: 15,
    top: 3
  },
  [`& .${classes.sectionWithSelectionIcon}`]: {
    fontSize: 12,
    color: '#FFF'
  }
}));
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => ({
  [`& .${classes.visibilityBadge}`]: {
    color: 'red',
    '& > span': {
      padding: 12,
      fontSize: 15
    }
  }
}));
const messages = (0, _reactIntl.defineMessages)({
  title: {
    id: 'ui.contributionActionMenu.title',
    defaultMessage: 'ui.contributionActionMenu.title'
  },
  spam: {
    id: 'ui.contributionActionMenu.spam',
    defaultMessage: 'ui.contributionActionMenu.spam'
  },
  aggressive: {
    id: 'ui.contributionActionMenu.aggressive',
    defaultMessage: 'ui.contributionActionMenu.aggressive'
  },
  vulgar: {
    id: 'ui.contributionActionMenu.vulgar',
    defaultMessage: 'ui.contributionActionMenu.vulgar'
  },
  poorContent: {
    id: 'ui.contributionActionMenu.poorContent',
    defaultMessage: 'ui.contributionActionMenu.poorContent'
  },
  offtopic: {
    id: 'ui.contributionActionMenu.offtopic',
    defaultMessage: 'ui.contributionActionMenu.offtopic'
  },
  footer: {
    id: 'ui.contributionActionMenu.footer',
    defaultMessage: 'ui.contributionActionMenu.footer'
  }
});

function ContributionActionsMenu(props) {
  // PROPS
  const {
    className,
    feedObjectId,
    feedObject,
    feedObjectType = _core.SCFeedObjectTypologyType.POST,
    commentObjectId,
    commentObject,
    onEditContribution,
    onHideContribution,
    onDeleteContribution,
    onRestoreContribution,
    onSuspendNotificationContribution,
    PopperProps = {}
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // INTL


  const intl = (0, _reactIntl.useIntl)(); // CONTEXT

  const scContext = (0, _react.useContext)(_core.SCContext);
  const scUserContext = (0, _react.useContext)(_core.SCUserContext);
  const scRoutingContext = (0, _core.useSCRouting)();
  const {
    enqueueSnackbar
  } = (0, _notistack.useSnackbar)(); // CONTRIBUTION STATE

  const {
    obj: feedObj,
    setObj: setFeedObj
  } = (0, _core.useSCFetchFeedObject)({
    id: feedObjectId,
    feedObject,
    feedObjectType
  });
  const {
    obj: commentObj,
    setObj: setCommentObj
  } = (0, _core.useSCFetchCommentObject)({
    id: commentObjectId,
    commentObject
  }); // GENERAL POPPER STATE

  const [open, setOpen] = (0, _react.useState)(false);
  const [openSection, setOpenSection] = (0, _react.useState)(null);
  const [isLoading, setIsLoading] = (0, _react.useState)(false); // MODERATION FLAGS STATE

  const [flagType, setFlagType] = (0, _react.useState)(null);
  const [isFlagging, setIsFlagging] = (0, _react.useState)(false); // MODERATION HIDE STATE

  const [hideType, setHideType] = (0, _react.useState)(null);
  const [hideFlagType, setHideFlagType] = (0, _react.useState)(null); // MODERATION DELETE STATE

  const [deleteType, setDeleteType] = (0, _react.useState)(null);
  const [deleteFlagType, setDeleteFlagType] = (0, _react.useState)(null); // CONFIRM ACTION DIALOG STATE

  const [openConfirmDialog, setOpenConfirmDialog] = (0, _react.useState)(false);
  const [currentAction, setCurrentAction] = (0, _react.useState)(null);
  const [currentActionLoading, setCurrentActionLoading] = (0, _react.useState)(null); // CONST

  const contributionObj = commentObj ? commentObj : feedObj;
  let popperRef = (0, _react.useRef)(null);
  /**
   * Intial extra sections to render, in addition to the GENERAL_SECTION
   * @return {array}
   */

  const getExtraSections = (0, _react.useMemo)(() => () => {
    let _extra = [];

    if (scUserContext.user && Boolean(contributionObj) && scUserContext.user.id !== contributionObj.author.id) {
      _extra.push(_ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION);
    } // Enable when backend is ready


    if (_core.UserUtils.isStaff(scUserContext.user)) {
      // admin or moderator
      _extra.push(_ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION);

      _extra.push(_ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION);
    }

    return _extra;
  }, [contributionObj]);
  /**
   * Extra sections to render in the popup
   */

  const extraSections = getExtraSections();
  /**
   * Handles open popup
   */

  function handleOpen() {
    if (scUserContext.user) {
      setIsLoading(true);
      Promise.all([fetchFlagStatus(), fetchModerationStatus()]).then(() => {
        setIsLoading(false);
      });
      setOpen(true);
    } else {
      scContext.settings.handleAnonymousAction();
    }
  }
  /**
   * Closes popup
   */


  function handleClose() {
    if (popperRef.current && popperRef.current.contains(event.target)) {
      return;
    }

    setOpen(false);

    if (rest.onClose) {
      rest.onClose();
    }
  }
  /**
   * Performs  notification suspension
   */


  const performSuspendNotification = (0, _react.useMemo)(() => () => {
    return _core.http.request({
      url: _core.Endpoints.UserSuspendContributionNotification.url({
        type: contributionObj.type,
        id: contributionObj.id
      }),
      method: _core.Endpoints.UserSuspendContributionNotification.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Handles stop notification for contributionObj
   * @param contribution
   */

  function handleSuspendContentNotification() {
    setCurrentActionLoading(_ContributionsActionsMenu.SUSPEND_NOTIFICATION_CONTRIBUTION);
    performSuspendNotification().then(data => {
      const _feedObj = Object.assign(feedObj, {
        suspended: !feedObj.suspended
      });

      setFeedObj(_feedObj);
      onSuspendNotificationContribution && onSuspendNotificationContribution(_feedObj);
      setCurrentActionLoading(null);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);

      setCurrentAction(null);
      setCurrentActionLoading(null);
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.actionError",
        defaultMessage: "ui.contributionActionMenu.actionError"
      }), {
        variant: 'error',
        autoHideDuration: 3000
      });
    });
  }
  /**
   * Get Status Flag
   */


  const performFetchFlagStatus = (0, _react.useMemo)(() => () => {
    return _core.http.request({
      url: _core.Endpoints.FlagStatus.url({
        type: contributionObj.type,
        id: contributionObj.id
      }),
      method: _core.Endpoints.FlagStatus.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Perform Flag
   */

  const performFlag = (0, _react.useMemo)(() => type => {
    return _core.http.request({
      url: _core.Endpoints.Flag.url({
        type: contributionObj.type,
        id: contributionObj.id
      }),
      method: _core.Endpoints.Flag.method,
      data: {
        flag_type: type
      }
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Get Status Flag
   */

  const performFetchModerationStatus = (0, _react.useMemo)(() => () => {
    return _core.http.request({
      url: _core.Endpoints.ModerateContributionStatus.url({
        contribution_type: contributionObj.type,
        id: contributionObj.id
      }),
      method: _core.Endpoints.ModerateContributionStatus.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Perform delete contribution
   */

  const performDeleteContribution = (0, _react.useMemo)(() => () => {
    const contributionType = contributionObj.type;
    return _core.http.request({
      url: contributionType === _core.SCCommentTypologyType ? _core.Endpoints.DeleteComment.url({
        id: contributionObj.id
      }) : _core.Endpoints.DeleteFeedObject.url({
        type: contributionType,
        id: contributionObj.id
      }),
      method: contributionType === _core.SCCommentTypologyType ? _core.Endpoints.DeleteComment.method : _core.Endpoints.DeleteFeedObject.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Perform restore contribution
   */

  const performRestoreContribution = (0, _react.useMemo)(() => () => {
    const contributionType = contributionObj.type;
    return _core.http.request({
      url: contributionType === _core.SCCommentTypologyType ? _core.Endpoints.RestoreComment.url({
        id: contributionObj.id
      }) : _core.Endpoints.RestoreFeedObject.url({
        type: contributionType,
        id: contributionObj.id
      }),
      method: contributionType === _core.SCCommentTypologyType ? _core.Endpoints.RestoreComment.method : _core.Endpoints.RestoreFeedObject.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Fetch initial flag status
   */

  function fetchFlagStatus() {
    if (contributionObj && extraSections.includes(_ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION)) {
      return performFetchFlagStatus().then(data => {
        // It could also be spam (=0)
        if (data['flag_type'] !== undefined && data['flag_type'] !== null) {
          setFlagType(data['flag_type']);
        }
      }).catch(error => {
        console.dir(error);

        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }

    return Promise.resolve();
  }
  /**
   * Fetch initial moderation status
   */


  function fetchModerationStatus() {
    if (contributionObj && (extraSections.includes(_ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION) || extraSections.includes(_ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION))) {
      return performFetchModerationStatus().then(data => {
        // It could also be spam (=0)
        if (data['flag_type'] !== undefined && data['flag_type'] !== null) {
          if (data.status === _Flagging.MODERATION_CONTRIBUTION_STATE_DELETED) {
            setDeleteType(data['flag_type']);
          } else if (data.status === _Flagging.MODERATION_CONTRIBUTION_STATE_HIDDEN) {
            setHideType(data['flag_type']);
          }
        }
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }

    return Promise.resolve();
  }
  /**
   * Perform contribute flagging by authenticated user
   * If the user authenticated is blocked, deny this action
   * @param type
   */


  function handleFlagContribution(type) {
    if (_core.UserUtils.isBlocked(scUserContext.user)) {
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.common.userBlocked",
        defaultMessage: "ui.common.userBlocked"
      }), {
        variant: 'warning',
        autoHideDuration: 3000
      });
    } else if (contributionObj && !isLoading && !isFlagging && type !== 'undefined') {
      setIsFlagging(true);
      performFlag(type).then(data => {
        setFlagType(flagType === type ? null : type);
        setIsFlagging(false);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Perform moderation
   */


  const performModerationContribution = (0, _react.useMemo)(() => (action, type) => {
    return _core.http.request({
      url: _core.Endpoints.ModerateContribution.url({
        id: contributionObj.id
      }),
      method: _core.Endpoints.ModerateContribution.method,
      data: Object.assign({
        contribution_type: contributionObj.type
      }, type ? {
        moderation_type: type
      } : {}, {
        action: action
      })
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [contributionObj]);
  /**
   * Perform contribute moderation hide
   * @param type
   */

  function handleHideContribution(type) {
    setHideFlagType(type);
    handleAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN);
  }
  /**
   * Perform contribute moderation delete
   * @param type
   */


  function handleDeleteContribution(type) {
    setDeleteFlagType(type);
    handleAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED);
  }
  /**
   * handle action
   */


  function handleAction(action) {
    if (_core.UserUtils.isBlocked(scUserContext.user) && [_ContributionsActionsMenu.EDIT_CONTRIBUTION, _ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN, _ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED].includes(action)) {
      // if user is blocked, deny edit and moderate
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.common.userBlocked",
        defaultMessage: "ui.common.userBlocked"
      }), {
        variant: 'warning',
        autoHideDuration: 3000
      });
      return;
    }

    if (action === _ContributionsActionsMenu.GET_CONTRIBUTION_PERMALINK) {
      (0, _string.copyTextToClipboard)(`${location.protocol}//${location.host}${scRoutingContext.url((0, _contribution.getContributionRouteName)(contributionObj), (0, _contribution.getRouteData)(contributionObj))}`).then(() => {
        setOpen(false);
        enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
          id: "ui.common.permanentLinkCopied",
          defaultMessage: "ui.common.permanentLinkCopied"
        }), {
          variant: 'success',
          autoHideDuration: 3000
        });
      });
      handleClose();
    } else if (action === _ContributionsActionsMenu.EDIT_CONTRIBUTION) {
      onEditContribution && onEditContribution(contributionObj);
      handleClose();
    } else if (action === _ContributionsActionsMenu.DELETE_CONTRIBUTION) {
      setCurrentAction(_ContributionsActionsMenu.DELETE_CONTRIBUTION);
      setOpenConfirmDialog(true);
      handleClose();
    } else if (action === _ContributionsActionsMenu.RESTORE_CONTRIBUTION) {
      setCurrentAction(_ContributionsActionsMenu.RESTORE_CONTRIBUTION);
      setOpenConfirmDialog(true);
      handleClose();
    } else if (action === _ContributionsActionsMenu.SUSPEND_NOTIFICATION_CONTRIBUTION) {
      setCurrentAction(_ContributionsActionsMenu.SUSPEND_NOTIFICATION_CONTRIBUTION);
      handleSuspendContentNotification();
    } else if (action === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN) {
      setCurrentAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN);
      setOpenConfirmDialog(true);
      handleClose();
    } else if (action === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED) {
      setCurrentAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED);
      setOpenConfirmDialog(true);
      handleClose();
    }
  }
  /**
   * Perform additional operations at the end of single action
   */


  function performPostConfirmAction(success) {
    if (success) {
      if ([_ContributionsActionsMenu.DELETE_CONTRIBUTION, _ContributionsActionsMenu.RESTORE_CONTRIBUTION].includes(currentAction)) {
        commentObj ? setCommentObj(Object.assign({}, commentObj, {
          deleted: currentAction === _ContributionsActionsMenu.DELETE_CONTRIBUTION
        })) : setFeedObj(Object.assign({}, feedObj, {
          deleted: currentAction === _ContributionsActionsMenu.DELETE_CONTRIBUTION
        }));
      } else if (currentAction === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN) {
        commentObj ? setCommentObj(Object.assign({}, commentObj, {
          collapsed: !commentObj.collapsed
        })) : setFeedObj(Object.assign({}, feedObj, {
          collapsed: !feedObj.collapsed
        }));
      } else if (currentAction === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED) {
        commentObj ? setCommentObj(Object.assign({}, commentObj, {
          deleted: !commentObj.deleted
        })) : setFeedObj(Object.assign({}, feedObj, {
          deleted: !feedObj.deleted
        }));
      }

      setCurrentActionLoading(null);
      setCurrentAction(null);
      setOpenConfirmDialog(false);
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.actionSuccess",
        defaultMessage: "ui.contributionActionMenu.actionSuccess"
      }), {
        variant: 'success',
        autoHideDuration: 3000
      });
    } else {
      setCurrentActionLoading(null);
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.actionError",
        defaultMessage: "ui.contributionActionMenu.actionError"
      }), {
        variant: 'error',
        autoHideDuration: 3000
      });
    }
  }
  /**
   * Delete a contribution
   */


  function handleConfirmedAction() {
    if (contributionObj && !isLoading && !currentActionLoading) {
      if (currentAction === _ContributionsActionsMenu.DELETE_CONTRIBUTION) {
        setCurrentActionLoading(_ContributionsActionsMenu.RESTORE_CONTRIBUTION);
        performDeleteContribution().then(data => {
          onDeleteContribution && onDeleteContribution(contributionObj);
          performPostConfirmAction(true);
        }).catch(error => {
          _core.Logger.error(_Errors.SCOPE_SC_UI, error);

          performPostConfirmAction(false);
        });
      } else if (currentAction === _ContributionsActionsMenu.RESTORE_CONTRIBUTION) {
        setCurrentActionLoading(_ContributionsActionsMenu.RESTORE_CONTRIBUTION);
        performRestoreContribution().then(data => {
          onRestoreContribution && onRestoreContribution(contributionObj);
          performPostConfirmAction(true);
        }).catch(error => {
          _core.Logger.error(_Errors.SCOPE_SC_UI, error);

          performPostConfirmAction(false);
        });
      } else if (currentAction === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN) {
        setCurrentActionLoading(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN);
        performModerationContribution(_Flagging.MODERATION_TYPE_ACTION_HIDE, hideFlagType).then(data => {
          setHideType(hideType === hideFlagType ? null : hideFlagType);
          setHideFlagType(null);
          onHideContribution && onHideContribution(contributionObj);
          performPostConfirmAction(true);
        }).catch(error => {
          _core.Logger.error(_Errors.SCOPE_SC_UI, error);

          performPostConfirmAction(false);
        });
      } else if (currentAction === _ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED) {
        setCurrentActionLoading(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED);
        performModerationContribution(_Flagging.MODERATION_TYPE_ACTION_DELETE, deleteFlagType).then(data => {
          setDeleteType(deleteType === deleteFlagType ? null : deleteFlagType);
          setDeleteFlagType(null);
          onDeleteContribution && onDeleteContribution(contributionObj);
          performPostConfirmAction(true);
        }).catch(error => {
          _core.Logger.error(_Errors.SCOPE_SC_UI, error);

          performPostConfirmAction(false);
        });
      }
    }
  }
  /**
   * Returns flag label based on type
   * @param flagType
   * @return {*}
   */


  function getReportName(flagType) {
    let name;

    switch (flagType) {
      case _Flagging.REPORT_SPAM:
        name = intl.formatMessage(messages.spam);
        break;

      case _Flagging.REPORT_AGGRESSIVE:
        name = intl.formatMessage(messages.aggressive);
        break;

      case _Flagging.REPORT_VULGAR:
        name = intl.formatMessage(messages.vulgar);
        break;

      case _Flagging.REPORT_POORCONTENT:
        name = intl.formatMessage(messages.poorContent);
        break;

      case _Flagging.REPORT_OFFTOPIC:
        name = intl.formatMessage(messages.offtopic);
        break;

      default:
        break;
    }

    return name;
  }
  /**
   * action
   * @param actionId
   */


  function handleOpenSection(sectionId) {
    if (sectionId) {
      if (sectionId === openSection) {
        setOpenSection(null);
      } else {
        setOpenSection(sectionId);
      }
    } else {
      setOpenSection(null);
    }
  }
  /**
   * Renders single flag item
   * @return {[{REPORTS}]}
   */


  function renderReports(section) {
    const handlerFunc = section === _ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION ? handleFlagContribution : section === _ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION ? handleHideContribution : handleDeleteContribution;
    return _Flagging.REPORTS.map((report, index) => /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      key: `${section}_${index}`,
      className: classes.subItem,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, {
      classes: {
        root: classes.selectedIcon
      }
    }, eval(`${section.split('_')[1]}Type`) === report && /*#__PURE__*/_react.default.createElement(_Icon.default, {
      color: "secondary"
    }, "check")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: getReportName(report),
      onClick: () => handlerFunc(report),
      classes: {
        root: classes.subItemText
      }
    })));
  }
  /**
   * Renders section flags actions
   */


  function renderFlagContributionSection() {
    const open = openSection === _ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION;
    return /*#__PURE__*/_react.default.createElement(_material.Box, null, !contributionObj.deleted && !contributionObj.collapsed && /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: isFlagging,
      onClick: () => handleOpenSection(_ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION)
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, flagType !== undefined && flagType !== null ? /*#__PURE__*/_react.default.createElement(_material.Badge, {
      classes: {
        badge: classes.sectionBadge
      },
      badgeContent: /*#__PURE__*/_react.default.createElement(_Icon.default, {
        className: classes.sectionWithSelectionIcon
      }, "check"),
      color: "primary"
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "outlined_flag")) : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "outlined_flag")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.flagContributionWithMotivation",
        defaultMessage: "ui.contributionActionMenu.flagContributionWithMotivation"
      })
    }), open ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_less") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_more")), /*#__PURE__*/_react.default.createElement(_material.Collapse, {
      in: open,
      timeout: "auto",
      unmountOnExit: true
    }, renderReports(_ContributionsActionsMenu.FLAG_CONTRIBUTION_SECTION), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: 'caption',
      component: 'div',
      className: classes.footerSubItems
    }, intl.formatMessage(messages.footer)))));
  }
  /**
   * Renders section hide actions
   */


  function renderHideContributionSection() {
    const open = openSection === _ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION;
    return /*#__PURE__*/_react.default.createElement(_material.Box, {
      key: _ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION
    }, !contributionObj.deleted && /*#__PURE__*/_react.default.createElement(_material.Box, null, hideType !== undefined && hideType !== null ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: Boolean(currentAction),
      onClick: () => handleAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_HIDDEN)
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "restore")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.restoreFromHidden",
        defaultMessage: "ui.contributionActionMenu.restoreFromHidden"
      }), ' ', "(", getReportName(hideType), ")")
    }))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: Boolean(currentAction),
      onClick: () => handleOpenSection(_ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION)
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "hide_image")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.hideContributionWithMotivation",
        defaultMessage: "ui.contributionActionMenu.hideContributionWithMotivation"
      })
    }), open ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_less") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_more")), /*#__PURE__*/_react.default.createElement(_material.Collapse, {
      in: open,
      timeout: "auto",
      unmountOnExit: true
    }, renderReports(_ContributionsActionsMenu.HIDE_CONTRIBUTION_SECTION)))));
  }
  /**
   * Renders section hidden actions
   */


  function renderDeleteContributionSection() {
    const open = openSection === _ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION;
    return /*#__PURE__*/_react.default.createElement(_material.Box, {
      key: _ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION
    }, !contributionObj.collapsed && !(contributionObj.deleted && !deleteType) && /*#__PURE__*/_react.default.createElement(_material.Box, null, deleteType !== undefined && deleteType !== null ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: Boolean(currentAction),
      onClick: () => handleAction(_ContributionsActionsMenu.MODERATE_CONTRIBUTION_DELETED)
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "restore_from_trash")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.restoreFromDeleted",
        defaultMessage: "ui.contributionActionMenu.restoreFromDeleted"
      }), ' ', "(", getReportName(deleteType), ")")
    }))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: Boolean(currentAction),
      onClick: () => handleOpenSection(_ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION)
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.deleteContributionWithMotivation",
        defaultMessage: "ui.contributionActionMenu.deleteContributionWithMotivation"
      })
    }), open ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_less") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "expand_more")), /*#__PURE__*/_react.default.createElement(_material.Collapse, {
      in: open,
      timeout: "auto",
      unmountOnExit: true
    }, renderReports(_ContributionsActionsMenu.DELETE_CONTRIBUTION_SECTION)))));
  }
  /**
   * Can authenticated user modify the contribution
   */


  function canModifyContribution() {
    return scUserContext.user && scUserContext.user.id === contributionObj.author.id && !contributionObj.deleted;
  }
  /**
   * Can authenticated user delete the contribution
   */


  function canDeleteContribution() {
    return scUserContext.user && scUserContext.user.id === contributionObj.author.id && !deleteType;
  }
  /**
   * Can authenticated user suspend notification for the contribution
   */


  function canSuspendNotificationContribution() {
    return scUserContext.user && scUserContext.user.id !== contributionObj.author.id && contributionObj && contributionObj.type !== _core.SCCommentTypologyType;
  }
  /**
   * Renders section general
   */


  function renderGeneralSection() {
    return /*#__PURE__*/_react.default.createElement(_material.Box, {
      key: _ContributionsActionsMenu.GENERAL_SECTION
    }, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "link")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.permanentLink",
        defaultMessage: "ui.contributionActionMenu.permanentLink"
      }),
      onClick: () => handleAction(_ContributionsActionsMenu.GET_CONTRIBUTION_PERMALINK),
      classes: {
        root: classes.itemText
      }
    })), canModifyContribution() && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "edit")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.editContribution",
        defaultMessage: "ui.contributionActionMenu.editContribution"
      }),
      onClick: () => handleAction(_ContributionsActionsMenu.EDIT_CONTRIBUTION),
      classes: {
        root: classes.itemText
      }
    })), canDeleteContribution() && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, currentActionLoading === _ContributionsActionsMenu.DELETE_CONTRIBUTION || currentActionLoading === _ContributionsActionsMenu.RESTORE_CONTRIBUTION ? /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
      size: 20
    }) : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete")), contributionObj.deleted ? /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.restoreContribution",
        defaultMessage: "ui.contributionActionMenu.restoreContribution"
      }),
      onClick: () => handleAction(_ContributionsActionsMenu.RESTORE_CONTRIBUTION),
      classes: {
        root: classes.itemText
      }
    }) : /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.deleteContribution",
        defaultMessage: "ui.contributionActionMenu.deleteContribution"
      }),
      onClick: () => handleAction(_ContributionsActionsMenu.DELETE_CONTRIBUTION),
      classes: {
        root: classes.itemText
      }
    })), canSuspendNotificationContribution() && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      className: classes.subItem,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, currentActionLoading === _ContributionsActionsMenu.SUSPEND_NOTIFICATION_CONTRIBUTION ? /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
      size: 20
    }) : contributionObj['suspended'] ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "notifications") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "notifications_off")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: contributionObj['suspended'] ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.enableNotificationContribution",
        defaultMessage: "ui.contributionActionMenu.enableNotificationContribution"
      }) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.contributionActionMenu.suspendNotificationContribution",
        defaultMessage: "ui.contributionActionMenu.suspendNotificationContribution"
      }),
      onClick: () => handleAction(_ContributionsActionsMenu.SUSPEND_NOTIFICATION_CONTRIBUTION),
      classes: {
        root: classes.itemText
      }
    })));
  }
  /**
   * Renders component
   */


  return /*#__PURE__*/_react.default.createElement(Root, {
    className: (0, _classnames.default)(classes.root, className)
  }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    ref: ref => {
      popperRef.current = ref;
    },
    "aria-haspopup": "true",
    onClick: handleOpen,
    className: classes.button,
    size: "medium"
  }, contributionObj.collapsed || contributionObj.deleted ? /*#__PURE__*/_react.default.createElement(_material.Badge, {
    badgeContent: contributionObj.collapsed ? /*#__PURE__*/_react.default.createElement(_Icon.default, null, "visibility_off") : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete"),
    classes: {
      badge: classes.visibilityBadge
    }
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "more_vert")) : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "more_vert")), /*#__PURE__*/_react.default.createElement(PopperRoot, _extends({
    open: open,
    anchorEl: popperRef.current,
    role: undefined,
    transition: true,
    className: classes.popper
  }, PopperProps, {
    placement: "bottom-end"
  }), ({
    TransitionProps,
    placement
  }) => /*#__PURE__*/_react.default.createElement(_material.Grow, _extends({}, TransitionProps, {
    style: {
      transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom'
    }
  }), /*#__PURE__*/_react.default.createElement(_material.Paper, {
    variant: 'outlined',
    className: classes.paper
  }, /*#__PURE__*/_react.default.createElement(_material.ClickAwayListener, {
    onClickAway: handleClose
  }, /*#__PURE__*/_react.default.createElement(_material.Box, null, isLoading || !feedObj && !commentObj ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 30
  }) : /*#__PURE__*/_react.default.createElement(_material.MenuList, null, renderGeneralSection(), Boolean(extraSections.length) && /*#__PURE__*/_react.default.createElement(_material.Divider, null), extraSections.map((s, i) => /*#__PURE__*/_react.default.createElement(_material.Box, {
    key: `es_${i}`
  }, eval(`render${(0, _material.capitalize)((0, _lodash.camelCase)(s))}`)())))))))), openConfirmDialog && /*#__PURE__*/_react.default.createElement(_ConfirmDialog.default, {
    open: openConfirmDialog,
    onConfirm: handleConfirmedAction,
    isUpdating: Boolean(currentActionLoading),
    onClose: () => setOpenConfirmDialog(false)
  }));
}