"use strict";

exports.__esModule = true;
exports.default = CommentActionsMenu;

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

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

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

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

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

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

var _CheckCircleOutline = _interopRequireDefault(require("@mui/icons-material/CheckCircleOutline"));

var _MoreVert = _interopRequireDefault(require("@mui/icons-material/MoreVert"));

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

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

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

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

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

var _notistack = require("notistack");

var _contribute = require("../../../utils/contribute");

const _excluded = ["commentObjectId", "commentObject", "feedObjectId", "feedObject", "feedObjectType", "onDelete", "onRestore", "onEdit"];

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 = 'SCCommentActionsMenu';
const classes = {
  root: `${PREFIX}-root`,
  button: `${PREFIX}-button`,
  popper: `${PREFIX}-popper`,
  paper: `${PREFIX}-paper`,
  footer: `${PREFIX}-footer`,
  item: `${PREFIX}-item`,
  itemText: `${PREFIX}-itemText`,
  selectedIcon: `${PREFIX}-selectedIcon`
};
const Root = (0, _styles.styled)(_Popper.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => ({
  zIndex: 2,
  [`& .${classes.paper}`]: {
    maxWidth: 200
  },
  [`& .${classes.footer}`]: {
    padding: '8px'
  },
  [`& .${classes.item}`]: {
    borderBottom: '1px solid #e5e5e5'
  },
  [`& .${classes.itemText}`]: {
    marginLeft: 7
  },
  [`& .${classes.selectedIcon}`]: {
    marginLeft: -17,
    position: 'relative',
    left: 5,
    '&.MuiListItemIcon-root': {
      minWidth: '21px'
    },
    '& svg': {
      fontSize: '1.2rem'
    }
  }
}));
const messages = (0, _reactIntl.defineMessages)({
  title: {
    id: 'ui.reportingMenu.title',
    defaultMessage: 'ui.reportingMenu.title'
  },
  spam: {
    id: 'ui.reportingMenu.spam',
    defaultMessage: 'ui.reportingMenu.spam'
  },
  aggressive: {
    id: 'ui.reportingMenu.aggressive',
    defaultMessage: 'ui.reportingMenu.aggressive'
  },
  vulgar: {
    id: 'ui.reportingMenu.vulgar',
    defaultMessage: 'ui.reportingMenu.vulgar'
  },
  poorContent: {
    id: 'ui.reportingMenu.poorContent',
    defaultMessage: 'ui.reportingMenu.poorContent'
  },
  offtopic: {
    id: 'ui.reportingMenu.offtopic',
    defaultMessage: 'ui.reportingMenu.offtopic'
  },
  footer: {
    id: 'ui.reportingMenu.footer',
    defaultMessage: 'ui.reportingMenu.footer'
  }
});

function CommentActionsMenu(props) {
  // PROPS
  const {
    commentObjectId,
    commentObject,
    feedObjectType = _core.SCFeedObjectTypologyType.POST,
    onDelete,
    onRestore,
    onEdit
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


  const intl = (0, _reactIntl.useIntl)();
  const scUser = (0, _react.useContext)(_core.SCUserContext);
  const scRoutingContext = (0, _core.useSCRouting)();
  const {
    enqueueSnackbar
  } = (0, _notistack.useSnackbar)(); // RETRIVE OBJECTS

  const {
    obj,
    setObj
  } = (0, _core.useSCFetchCommentObject)({
    id: commentObjectId,
    commentObject
  }); // STATE

  const [flagType, setFlagType] = (0, _react.useState)(null);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [isFlagging, setIsFlagging] = (0, _react.useState)(false);
  const [open, setOpen] = (0, _react.useState)(false);
  const [openDeleteCommentDialog, setOpenDeleteCommentDialog] = (0, _react.useState)(false);
  const [isDeletingComment, setIsDeletingComment] = (0, _react.useState)(false);
  const [openRestoreCommentDialog, setOpenRestoreCommentDialog] = (0, _react.useState)(false);
  const [isRestoringComment, setIsRestoringComment] = (0, _react.useState)(false); // REFS

  let popperRef = (0, _react.useRef)(null);
  /**
   * Get Status Flag
   */

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

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

  const performFlag = (0, _react.useMemo)(() => type => {
    return _core.http.request({
      url: _core.Endpoints.Flag.url({
        type: _core.SCCommentTypologyType,
        id: obj.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);
    });
  }, [obj]);
  /**
   * Fetch initial flag status
   */

  function fetchFlagStatus() {
    if (obj && !isLoading) {
      setIsLoading(true);
      fetchFetchFlagStatus().then(data => {
        setFlagType(data['flag_type']);
        setIsLoading(false);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Perform contribute flagging by authenticated user
   * @param type
   */


  function handleFlag(type) {
    if (obj && !isLoading && !isFlagging && type) {
      setIsFlagging(true);
      performFlag(type).then(data => {
        setFlagType(flagType === type ? null : type);
        setIsFlagging(false);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Handle permanent link
   */


  function handlePermanentLink() {
    (0, _string.copyTextToClipboard)(`${location.protocol}//${location.host}${scRoutingContext.url(_core.SCRoutes.COMMENT_ROUTE_NAME, (0, _contribute.getRouteData)(obj))}`).then(() => {
      setOpen(false);
      enqueueSnackbar( /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.commentObject.commentActionsMenu.permanentLinkCopied",
        defaultMessage: "ui.commentObject.commentActionsMenu.permanentLinkCopied"
      }), {
        variant: 'success'
      });
    });
  }
  /**
   * Handle edit comment
   */


  function handleEditComment() {
    setOpen(false);
    onEdit && onEdit(obj);
  }
  /**
   * Perform Delete comment
   */


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

      return Promise.resolve(res.data);
    });
  }, [obj]);
  /**
   * Handle delete comment
   */

  function deleteComment() {
    if (obj && !isLoading) {
      setIsDeletingComment(true);
      performDeleteComment().then(data => {
        onDelete && onDelete(commentObject);
        setIsDeletingComment(false);
        setOpenDeleteCommentDialog(false);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Perform Restore comment
   */


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

      return Promise.resolve(res.data);
    });
  }, [obj]);
  /**
   * Handle restore comment
   */

  function restoreComment() {
    if (obj && !isLoading) {
      setIsRestoringComment(true);
      performRestoreComment().then(data => {
        onRestore && onRestore(commentObject);
        setIsRestoringComment(false);
        setOpenRestoreCommentDialog(false);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Handle open flagging popup, retrive always the flag status (if exist)
   */


  function handleOpenMenu() {
    setOpen(true);
    fetchFlagStatus();
  }
  /**
   * Close the flagging popup
   */


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

    setOpen(false);

    if (rest.onClose) {
      rest.onClose();
    }
  }
  /**
   * Return flag label based on type
   * @param flagType
   * @return {*}
   */


  function getFlagName(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;
  }
  /**
   * Render single flag item
   * @return {[{REPORTS}]}
   */


  function renderFlags() {
    return _Flagging.REPORTS.map((flag, index) => /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
      key: index,
      className: classes.item,
      disabled: isFlagging
    }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, {
      classes: {
        root: classes.selectedIcon
      }
    }, flagType === flag && /*#__PURE__*/_react.default.createElement(_CheckCircleOutline.default, {
      color: "secondary"
    })), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: getFlagName(flag),
      onClick: () => handleFlag(flag),
      classes: {
        root: classes.itemText
      }
    })));
  }

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    ref: ref => {
      popperRef.current = ref;
    },
    "aria-haspopup": "true",
    onClick: handleOpenMenu,
    className: classes.button,
    size: "medium"
  }, /*#__PURE__*/_react.default.createElement(_MoreVert.default, null)), /*#__PURE__*/_react.default.createElement(Root, {
    open: open,
    anchorEl: popperRef.current,
    role: undefined,
    transition: true,
    className: classes.popper,
    placement: "bottom-start"
  }, ({
    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: handleCloseMenu
  }, isLoading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 30
  }) : /*#__PURE__*/_react.default.createElement(_material.MenuList, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    onClick: handlePermanentLink
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.commentObject.commentActionsMenu.permanentLink",
    defaultMessage: "ui.commentObject.commentActionsMenu.permanentLink"
  })), scUser.user.id === obj.author.id ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    onClick: handleEditComment
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.commentObject.commentActionsMenu.edit",
    defaultMessage: "ui.commentObject.commentActionsMenu.edit"
  })), obj.deleted && scUser.user && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    onClick: () => setOpenRestoreCommentDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.commentObject.commentActionsMenu.restore",
    defaultMessage: "ui.commentObject.commentActionsMenu.restore"
  })), !obj.deleted && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    onClick: () => setOpenDeleteCommentDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.commentObject.commentActionsMenu.delete",
    defaultMessage: "ui.commentObject.commentActionsMenu.delete"
  }))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Divider, null), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'body1',
    sx: {
      paddingLeft: '8px',
      fontWeight: '700'
    },
    gutterBottom: true
  }, intl.formatMessage(messages.title)), renderFlags(), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'caption',
    component: 'div',
    className: classes.footer
  }, intl.formatMessage(messages.footer)))))))), (openDeleteCommentDialog || openRestoreCommentDialog) && /*#__PURE__*/_react.default.createElement(_ConfirmDialog.default, {
    open: openDeleteCommentDialog || openRestoreCommentDialog,
    title: openRestoreCommentDialog ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.commentObject.commentActionsMenu.restoreCommentTitleDialog",
      defaultMessage: "ui.commentObject.commentActionsMenu.restoreCommentTitleDialog"
    }) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.commentObject.commentActionsMenu.deleteCommentTitleDialog",
      defaultMessage: "ui.commentObject.commentActionsMenu.deleteCommentTitleDialog"
    }),
    content: openRestoreCommentDialog ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.commentObject.commentActionsMenu.restoreCommentContentDialog",
      defaultMessage: "ui.commentObject.commentActionsMenu.restoreCommentContentDialog"
    }) : /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.commentObject.commentActionsMenu.deleteCommentContentDialog",
      defaultMessage: "ui.commentObject.commentActionsMenu.deleteCommentContentDialog"
    }),
    btnConfirm: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.changePicture.dialog.confirm",
      defaultMessage: "ui.changePicture.dialog.confirm"
    }),
    onConfirm: openRestoreCommentDialog ? restoreComment : deleteComment,
    isUpdating: isDeletingComment || isRestoringComment,
    onClose: openRestoreCommentDialog ? () => setOpenRestoreCommentDialog(false) : () => setOpenDeleteCommentDialog(false)
  }));
}