"use strict";

exports.__esModule = true;
exports.default = ReportingFlagMenu;

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("../CentralProgress"));

const _excluded = ["id", "feedObject", "feedObjectType"];

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 = 'SCFeedObjectReportMenu';
const classes = {
  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,
    padding: '7px 13px'
  },
  [`& .${classes.footer}`]: {
    marginTop: 15
  },
  [`& .${classes.item}`]: {
    borderBottom: '1px solid #e5e5e5'
  },
  [`& .${classes.itemText}`]: {
    marginLeft: 7
  },
  [`& .${classes.selectedIcon}`]: {
    marginLeft: -17,
    '&.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 ReportingFlagMenu(props) {
  // PROPS
  const {
    id = null,
    feedObject = null,
    feedObjectType = _core.SCFeedObjectTypologyType.POST
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // INTL


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

  const {
    obj,
    setObj
  } = (0, _core.useSCFetchFeedObject)({
    id,
    feedObject,
    feedObjectType
  });
  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);
  let popperRef = (0, _react.useRef)(null);
  /**
   * Get Status Flag
   */

  const performFlagStatus = (0, _react.useMemo)(() => () => {
    return _core.http.request({
      url: _core.Endpoints.FlagStatus.url({
        type: feedObjectType,
        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: feedObjectType,
        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);
      performFlagStatus().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);
      });
    }
  }
  /**
   * Handles open flagging popup, retrive always the flag status (if exist)
   */


  function handleOpen() {
    setOpen(true);
    fetchFlagStatus();
  }
  /**
   * Closes the flagging popup
   */


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

    setOpen(false);

    if (rest.onClose) {
      rest.onClose();
    }
  }
  /**
   * Returns 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;
  }
  /**
   * Renders 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
      }
    })));
  }
  /**
   * Renders component
   */


  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    ref: ref => {
      popperRef.current = ref;
    },
    "aria-haspopup": "true",
    onClick: handleOpen,
    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: handleClose
  }, isLoading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 30
  }) : /*#__PURE__*/_react.default.createElement(_material.MenuList, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'body1',
    gutterBottom: true
  }, intl.formatMessage(messages.title)), renderFlags(), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'caption',
    component: 'div',
    className: classes.footer
  }, intl.formatMessage(messages.footer))))))));
}