"use strict";

exports.__esModule = true;
exports.default = MessageEditor;

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

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

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

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

var _emojiPickerReact = _interopRequireDefault(require("emoji-picker-react"));

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

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

var _index = _interopRequireDefault(require("./MessageMediaUploader/index"));

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

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

const _excluded = ["autoHide", "className", "send", "isSending", "getMessage", "getMessageFile"];

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 = 'SCMessageEditor';
const classes = {
  root: `${PREFIX}-root`,
  messageInput: `${PREFIX}-message-input`,
  sendMediaSection: `${PREFIX}-send-media-section`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  width: '100%',
  display: 'inline-block',
  [`& .${classes.messageInput}`]: {
    width: '100%',
    '& .MuiOutlinedInput-root': {
      borderRadius: '20px'
    }
  },
  [`& .${classes.sendMediaSection}`]: {
    backgroundColor: theme.palette.grey['A200'],
    display: 'flex',
    justifyContent: 'center'
  }
}));

/**
 *
 > API documentation for the Community-UI Message Editor component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {MessageEditor} from '@selfcommunity/ui';
 ```

 #### Component Name

 The name `SCMessageEditor` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCMessageEditor-root|Styles applied to the root element.|
 |messageInput|.SCMessageEditor-card|Styles applied to the message input element.|
 |sendMediaSection|.SCMessageEditor-send-media-section|Styles applied to the send media section.|

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

  const {
    autoHide = null,
    className = null,
    send = null,
    isSending = null,
    getMessage = null,
    getMessageFile = null
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const [message, setMessage] = (0, _react.useState)('');
  const [messageFile, setMessageFile] = (0, _react.useState)(null);
  const [show, setShow] = (0, _react.useState)(false);

  const [emojiAnchorEl, setEmojiAnchorEl] = _react.default.useState(null);

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

  const open = Boolean(anchorEl);
  const [openMediaSection, setOpenMediaSection] = (0, _react.useState)(false); // CONTEXT

  const scContext = (0, _react.useContext)(_core.SCContext); // REF

  const ref = (0, _react.useRef)(null); // HANDLERS

  const handleMediaSectionClose = () => {
    setOpenMediaSection(false);
    setShow(false);
  };

  const handleMessageFile = f => {
    setMessageFile(f);
    getMessageFile(f);
  };

  const handleMessageSend = () => {
    send();
    setMessage('');
    setOpenMediaSection(false);
    setShow(false);
  };

  const handleMessageInput = event => {
    setMessage(event.target.value);
    setShow(true);
    getMessage(event.target.value);
  };

  const handleToggleEmoji = event => {
    setEmojiAnchorEl(emojiAnchorEl ? null : event.currentTarget);
  };

  const handleEmojiClick = (event, emojiObject) => {
    const cursor = ref.current.selectionStart;
    const text = message.slice(0, cursor) + emojiObject.emoji;
    setMessage(text);
    getMessage(text);
    setShow(true);
  };

  if (!autoHide) {
    return /*#__PURE__*/_react.default.createElement(Root, _extends({}, rest, {
      className: (0, _classnames.default)(classes.root, className)
    }), openMediaSection ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.sendMediaSection
    }, show && /*#__PURE__*/_react.default.createElement(_material.Button, {
      disabled: !messageFile,
      onClick: handleMessageSend,
      variant: "outlined"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.messageEditor.button.send",
      defaultMessage: "ui.messageEditor.button.send"
    }))), /*#__PURE__*/_react.default.createElement(_index.default, {
      open: openMediaSection,
      onClose: handleMediaSectionClose,
      forwardMessageFile: handleMessageFile,
      onFileUploaded: () => setShow(true),
      onFileCleared: () => setShow(false)
    })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.TextField, {
      size: "small",
      ref: ref,
      className: classes.messageInput,
      multiline: true,
      placeholder: "Aa",
      value: message,
      onChange: handleMessageInput,
      InputProps: {
        endAdornment: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.InputAdornment, {
          position: "end"
        }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
          onClick: () => setOpenMediaSection(true)
        }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "attach_file"))), /*#__PURE__*/_react.default.createElement(_material.InputAdornment, {
          position: "end"
        }, /*#__PURE__*/_react.default.createElement(_material.Stack, null, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
          size: "small",
          onClick: handleToggleEmoji
        }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "sentiment_satisfied_alt")), /*#__PURE__*/_react.default.createElement(_material.Popover, {
          open: Boolean(emojiAnchorEl),
          anchorEl: emojiAnchorEl,
          onClose: handleToggleEmoji,
          anchorOrigin: {
            vertical: 'top',
            horizontal: 'right'
          },
          transformOrigin: {
            vertical: 'bottom',
            horizontal: 'left'
          },
          sx: theme => {
            return {
              zIndex: theme.zIndex.tooltip
            };
          }
        }, /*#__PURE__*/_react.default.createElement(_emojiPickerReact.default, {
          onEmojiClick: handleEmojiClick
        })))), /*#__PURE__*/_react.default.createElement(_material.IconButton, {
          disabled: isSending,
          onClick: handleMessageSend
        }, show && /*#__PURE__*/_react.default.createElement(_Icon.default, null, "send"))))
      }
    })));
  }

  return null;
}