"use strict";

exports.__esModule = true;
exports.default = ReplyCommentObject;

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

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

var _Widget = _interopRequireDefault(require("../../Widget"));

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

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

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

var _Editor = _interopRequireDefault(require("../../Editor"));

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

var _lab = require("@mui/lab");

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

var _BaseItemButton = _interopRequireDefault(require("../../../shared/BaseItemButton"));

const _excluded = ["className", "elevation", "autoFocus", "inline", "onReply", "onSave", "onCancel", "readOnly", "text", "ReplyBoxProps"];

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)({
  reply: {
    id: 'ui.commentObject.replyComment.reply',
    defaultMessage: 'ui.commentObject.replyComment.reply'
  },
  save: {
    id: 'ui.commentObject.replyComment.save',
    defaultMessage: 'ui.commentObject.replyComment.save'
  },
  cancel: {
    id: 'ui.commentObject.replyComment.cancel',
    defaultMessage: 'ui.commentObject.replyComment.cancel'
  }
});
const PREFIX = 'SCReplyCommentObject';
const classes = {
  root: `${PREFIX}-root`,
  comment: `${PREFIX}-comment`,
  avatar: `${PREFIX}-avatar`
};
const Root = (0, _styles.styled)(_BaseItemButton.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  padding: '1px',
  overflow: 'visible',
  [`&.${classes.root}`]: {
    '& .SCBaseItemButton-content': {
      alignItems: 'flex-start',
      '& .SCBaseItemButton-text': {
        marginTop: 0,
        '& .SCBaseItemButton-secondary': {
          overflow: 'visible'
        }
      }
    }
  },
  [`& .${classes.comment}`]: {
    overflow: 'visible'
  }
}));

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

  const {
    className,
    elevation = 0,
    autoFocus = false,
    inline = false,
    onReply,
    onSave,
    onCancel,
    readOnly = false,
    text = '',
    ReplyBoxProps = {
      variant: 'outlined'
    }
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


  const scUserContext = (0, _react.useContext)(_core.SCUserContext);
  const intl = (0, _reactIntl.useIntl)(); // RETRIEVE OBJECTS

  const [html, setHtml] = (0, _react.useState)(text); // REFS

  let editor = /*#__PURE__*/_react.default.createRef();
  /**
   * When ReplyCommentObject is mount
   * if autoFocus === true focus on editor
   */


  (0, _react.useEffect)(() => {
    autoFocus && handleEditorFocus();
  }, [autoFocus]);
  /**
   * Focus on editor
   */

  const handleEditorFocus = () => {
    if (editor.current) {
      editor.current.focus();
    }
  };
  /**
   * Handle Replay
   */


  const handleReply = () => {
    onReply && onReply(html);
  };
  /**
   * Handle Save
   */


  const handleSave = () => {
    onSave && onSave(html);
  };
  /**
   * Handle cancel save
   */


  const handleCancel = () => {
    onCancel && onCancel();
  };
  /**
   * Handle Editor change
   */


  const handleChangeText = value => {
    setHtml(value);
  };
  /**
   * Check if editor is empty
   */


  const isEditorEmpty = (0, _react.useMemo)(() => () => {
    const _html = html.trim();

    return _html === '' || _html === '<p></p>';
  }, [html]); // RENDER

  return /*#__PURE__*/_react.default.createElement(Root, _extends({}, rest, {
    disableTypography: true,
    elevation: elevation,
    ButtonBaseProps: {
      disableTouchRipple: true,
      onClick: handleEditorFocus,
      component: 'div'
    },
    className: (0, _classnames.default)(classes.root, className),
    image: !scUserContext.user ? /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      variant: "circular",
      className: classes.avatar
    }) : /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      alt: scUserContext.user.username,
      variant: "circular",
      src: scUserContext.user.avatar,
      classes: {
        root: classes.avatar
      }
    }),
    secondary: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Widget.default, _extends({
      className: classes.comment,
      elevation: elevation
    }, ReplyBoxProps), /*#__PURE__*/_react.default.createElement(_Editor.default, {
      onRef: e => {
        editor = e;
      },
      onChange: handleChangeText,
      defaultValue: html,
      readOnly: readOnly
    }), !isEditorEmpty() && /*#__PURE__*/_react.default.createElement(_material.Stack, {
      direction: "row",
      spacing: 2,
      sx: {
        mb: 1,
        ml: 1
      }
    }, onReply && /*#__PURE__*/_react.default.createElement(_lab.LoadingButton, {
      variant: "outlined",
      size: "small",
      onClick: handleReply,
      loading: readOnly
    }, intl.formatMessage(messages.reply)), onSave && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, onCancel && /*#__PURE__*/_react.default.createElement(_lab.LoadingButton, {
      variant: 'text',
      size: "small",
      onClick: handleCancel,
      loading: readOnly,
      color: "inherit"
    }, intl.formatMessage(messages.cancel)), /*#__PURE__*/_react.default.createElement(_lab.LoadingButton, {
      variant: "outlined",
      size: "small",
      onClick: handleSave,
      loading: readOnly
    }, intl.formatMessage(messages.save))))))
  }));
}