"use strict";

exports.__esModule = true;
exports.default = Share;

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

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

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

var _LoadingButton = _interopRequireDefault(require("@mui/lab/LoadingButton"));

var _SharesDialog = _interopRequireDefault(require("./SharesDialog"));

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

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

var _MenuItem = _interopRequireDefault(require("@mui/material/MenuItem"));

var _ListItemIcon = _interopRequireDefault(require("@mui/material/ListItemIcon"));

var _Composer = _interopRequireDefault(require("../../../Composer"));

var _Media = require("../../../../constants/Media");

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

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

var _notistack = require("notistack");

var _Skeleton = _interopRequireDefault(require("@mui/material/Skeleton"));

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

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["className", "feedObjectId", "feedObject", "feedObjectType", "withAction", "withAudience", "inlineAction"];

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 messages = (0, _reactIntl.defineMessages)({
  shares: {
    id: 'ui.feedObject.share.shares',
    defaultMessage: 'ui.feedObject.share.shares'
  },
  share: {
    id: 'ui.feedObject.share.share',
    defaultMessage: 'ui.feedObject.share.share'
  },
  shareInCategories: {
    id: 'ui.feedObject.share.shareInCategories',
    defaultMessage: 'ui.feedObject.share.shareInCategories'
  }
});
const PREFIX = 'SCShareObject';
const classes = {
  root: `${PREFIX}-root`,
  divider: `${PREFIX}-divider`,
  inline: `${PREFIX}-inline`,
  actionButton: `${PREFIX}-action-button`,
  inlineActionButton: `${PREFIX}-inline-action-button`,
  viewAudienceButton: `${PREFIX}-view-audience-button`,
  shareMenuIcon: `${PREFIX}-share-Menu-icon`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  flexDirection: 'column',
  [`&.${classes.inline}`]: {
    flexDirection: 'row-reverse'
  },
  [`& .${classes.inlineActionButton}`]: {
    minWidth: 30
  },
  [`& .${classes.divider}`]: {
    width: '100%',
    borderBottom: 0
  },
  [`& .${classes.viewAudienceButton}`]: {
    height: 32,
    fontSize: 15,
    textTransform: 'capitalize',
    '& p': {
      fontSize: '0.9rem'
    }
  },
  [`&.${classes.shareMenuIcon}`]: {
    minWidth: 30
  }
}));

function Share(inProps) {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    className = null,
    feedObjectId = null,
    feedObject = null,
    feedObjectType = _core.SCFeedObjectTypologyType.POST,
    withAction = true,
    withAudience = true,
    inlineAction = true
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const {
    obj,
    setObj
  } = (0, _core.useSCFetchFeedObject)({
    id: feedObjectId,
    feedObject,
    feedObjectType
  });
  const [isSharing, setIsSharing] = (0, _react.useState)(false);
  const [isComposerOpen, setIsComposerOpen] = (0, _react.useState)(false);
  const [composerShareProps, setComposerShareProps] = (0, _react.useState)(null);
  const [openSharesDialog, setOpenSharesDialog] = (0, _react.useState)(false);

  const [anchorEl, setAnchorEl] = _react.default.useState(null); // CONTEXT


  const scContext = (0, _core.useSCContext)();
  const scUserContext = (0, _core.useSCUser)();
  const {
    enqueueSnackbar
  } = (0, _notistack.useSnackbar)(); // INTL

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

  const handleOpenShareMenu = event => {
    if (!scUserContext.user) {
      scContext.settings.handleAnonymousAction();
    } else {
      setAnchorEl(event.currentTarget);
    }
  };

  const handleClose = () => {
    setAnchorEl(null);
  };
  /**
   * Open/Close dialog shares
   */


  function handleToggleSharesDialog() {
    setOpenSharesDialog(!openSharesDialog);
  }
  /**
   * Handles Composer onClose
   */


  function handleComposerOnClose() {
    setIsSharing(false);
    setIsComposerOpen(false);
  }
  /**
   * Handles Composer onSuccess
   */


  function handleComposerOnSuccess() {
    handleComposerOnClose();
  }
  /**
   * Performs follow/unfollow
   * Post, Discussion, Status
   */


  const performCreateMediaShare = (0, _react.useMemo)(() => () => {
    // Define share object id
    let sharedObjectId = obj.id; // Avoid to re-share an object with a shared_object in medias

    const shareMedias = obj.medias.filter(media => media.type === _Media.MEDIA_TYPE_SHARE);

    if (shareMedias.length) {
      sharedObjectId = shareMedias[0].embed.metadata.id;
    }

    return _core.http.request({
      url: _core.Endpoints.ComposerMediaCreate.url(),
      method: _core.Endpoints.ComposerMediaCreate.method,
      data: {
        type: _Media.MEDIA_TYPE_SHARE,
        shared_object: sharedObjectId
      }
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, [obj]);
  /**
   * Performs the contribute sharing
   */

  function share(inCategories) {
    if (!scUserContext.user) {
      scContext.settings.handleAnonymousAction();
    } else {
      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 {
        setIsSharing(true);
        performCreateMediaShare().then(data => {
          setComposerShareProps(Object.assign({
            medias: [data]
          }, inCategories ? {
            categories: obj.categories
          } : {}));
          setIsComposerOpen(true);
        }).catch(error => {
          _core.Logger.error(_Errors.SCOPE_SC_UI, error);

          setIsSharing(false);
        });
      }
    }
  }
  /**
   * Renders audience with detail dialog
   * @return {JSX.Element}
   */


  function renderAudience() {
    const sharesCount = obj.share_count;
    let audience;

    if (withAudience) {
      if (!obj) {
        audience = /*#__PURE__*/_react.default.createElement(_material.Button, {
          variant: "text",
          size: "small",
          disabled: true,
          color: "inherit"
        }, /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
          animation: "wave",
          height: 18,
          width: 50
        }));
      } else {
        audience = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
          variant: "text",
          size: "small",
          onClick: handleToggleSharesDialog,
          disabled: sharesCount < 1,
          color: "inherit",
          classes: {
            root: classes.viewAudienceButton
          }
        }, `${intl.formatMessage(messages.shares, {
          total: sharesCount
        })}`), openSharesDialog && sharesCount > 0 && /*#__PURE__*/_react.default.createElement(_SharesDialog.default, {
          feedObject: obj,
          open: openSharesDialog,
          onClose: handleToggleSharesDialog
        }));
      }
    }

    return audience;
  }
  /**
   * Renders vote action if withAction==true
   * @return {JSX.Element}
   */


  function renderShareBtn() {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, withAction && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, !inlineAction && withAudience && /*#__PURE__*/_react.default.createElement(_material.Divider, {
      className: classes.divider
    }), /*#__PURE__*/_react.default.createElement(_material.Tooltip, {
      title: `${intl.formatMessage(messages.share)}`
    }, /*#__PURE__*/_react.default.createElement(_LoadingButton.default, {
      loading: isSharing,
      onClick: handleOpenShareMenu,
      color: "inherit",
      classes: {
        root: (0, _classnames.default)(classes.actionButton, {
          [classes.inlineActionButton]: inlineAction
        })
      }
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
      fontSize: 'large'
    }, "share"))), /*#__PURE__*/_react.default.createElement(_material.Menu, {
      anchorEl: anchorEl,
      open: Boolean(anchorEl),
      onClose: handleClose,
      onClick: handleClose,
      PaperProps: {
        elevation: 0,
        sx: {
          overflow: 'visible',
          filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))',
          mt: 1.5,
          '&:before': {
            content: '""',
            display: 'block',
            position: 'absolute',
            top: 0,
            right: 14,
            width: 10,
            height: 10,
            bgcolor: 'background.paper',
            transform: 'translateY(-50%) rotate(45deg)',
            zIndex: 0
          }
        }
      },
      transformOrigin: {
        horizontal: 'right',
        vertical: 'top'
      },
      anchorOrigin: {
        horizontal: 'right',
        vertical: 'bottom'
      }
    }, /*#__PURE__*/_react.default.createElement(_MenuItem.default, {
      onClick: () => share(false)
    }, /*#__PURE__*/_react.default.createElement(_ListItemIcon.default, {
      classes: {
        root: classes.shareMenuIcon
      }
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
      fontSize: "small"
    }, "redo")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.feedObject.share.shareNow",
        defaultMessage: "ui.feedObject.share.shareNow"
      })
    })), obj.categories.length > 0 && /*#__PURE__*/_react.default.createElement(_MenuItem.default, {
      onClick: () => share(true)
    }, /*#__PURE__*/_react.default.createElement(_ListItemIcon.default, {
      classes: {
        root: classes.shareMenuIcon
      }
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
      fontSize: "small"
    }, "share")), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
      primary: intl.formatMessage(messages.shareInCategories, {
        categories: obj.categories.map(c => c.name).join(', ')
      })
    }))), isComposerOpen && /*#__PURE__*/_react.default.createElement(_Composer.default, {
      open: isComposerOpen,
      defaultValue: composerShareProps,
      onClose: handleComposerOnClose,
      onSuccess: handleComposerOnSuccess,
      maxWidth: "sm",
      fullWidth: true,
      scroll: "body"
    })));
  }
  /**
   * Renders share action
   */


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: (0, _classnames.default)(classes.root, className, {
      [classes.inline]: inlineAction
    })
  }, rest), renderAudience(), renderShareBtn());
}