"use strict";

exports.__esModule = true;
exports.default = Message;

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

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

var _List = _interopRequireDefault(require("@mui/material/List"));

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

var _Skeleton = _interopRequireDefault(require("./Skeleton"));

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

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

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

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

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

var _AutoPlayer = _interopRequireDefault(require("../../shared/AutoPlayer"));

var _reactLazyload = _interopRequireDefault(require("react-lazyload"));

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

const _excluded = ["id", "autoHide", "message", "className", "snippetType", "onMouseEnter", "onMouseLeave", "isHovering", "loggedUser", "onDeleteIconClick"];

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 = 'SCMessage';
const classes = {
  root: `${PREFIX}-root`,
  selected: `${PREFIX}-selected`,
  info: `${PREFIX}-info`,
  messageBox: `${PREFIX}-message-box`,
  messageTime: `${PREFIX}-message-time`,
  unread: `${PREFIX}-unread`,
  hide: `${PREFIX}-hide`,
  img: `${PREFIX}-img`,
  downloadButton: `${PREFIX}-download-button`,
  documentFile: `${PREFIX}-document-file`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  [`& .${classes.info}`]: {
    display: 'flex',
    justifyContent: 'space-between'
  },
  [`& .${classes.messageBox}`]: {
    margin: 'auto',
    padding: '16px',
    borderRadius: '20px'
  },
  [`& .${classes.messageTime}`]: {
    marginTop: '5px',
    display: 'flex',
    justifyContent: 'flex-end'
  },
  [`& .${classes.img}`]: {
    width: 250,
    height: 200
  },
  [`& .${classes.downloadButton}`]: {
    backgroundColor: theme.palette.common.white,
    marginBottom: '5px'
  },
  [`& .${classes.documentFile}`]: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center'
  }
}));

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

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCMessage-root|Styles applied to the root element.|
 |selected|.SCMessage-selected|Styles applied to the selected element.|
 |info|.SCMessage-info|Styles applied to the info section.|
 |messageBox|.SCMessage-message-box|Styles applied to the message box element.|
 |messageTime|.SCMessage-message-time|Styles applied to the message time element.|
 |unread|.SCMessage-unread|Styles applied to the unread element.|
 |img|.SCMessage-img|Styles applied to the img element.|
 |downloadButton|.SCMessage-download-button|Styles applied to the download button element.|
 |documentFile|.SCMessage-document-file|Styles applied to the message file element.|


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

  const {
    id = null,
    autoHide = false,
    message = null,
    className = null,
    snippetType = true,
    onMouseEnter = null,
    onMouseLeave = null,
    isHovering = null,
    loggedUser = null,
    onDeleteIconClick = null
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // INTL


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

  const hasFile = message ? message.file : null;
  const isNew = message ? message.thread_status === 'new' : null; // CONTEXT

  const scUserContext = (0, _react.useContext)(_core.SCUserContext);

  if (!message) {
    return /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
      elevation: 0
    });
  }

  function bytesToSize(bytes) {
    return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
  } // RENDERING


  const renderMessageFile = m => {
    if (!m) {
      return null;
    }

    let section = null;

    if (m.file) {
      let type = m.file.mimetype;
      let isPdf = type === 'application/pdf';
      let src = message.file.url;

      switch (true) {
        case type.startsWith(_core.SCMessageFileType.IMAGE):
          section = /*#__PURE__*/_react.default.createElement(_material.Box, {
            className: classes.img
          }, /*#__PURE__*/_react.default.createElement("img", {
            style: {
              height: '100%',
              width: '100%'
            },
            src: src,
            loading: "lazy",
            alt: 'img'
          }));
          break;

        case type.startsWith(_core.SCMessageFileType.VIDEO):
          section = /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_AutoPlayer.default, {
            url: src,
            width: '100%'
          }));
          break;

        case type.startsWith(_core.SCMessageFileType.DOCUMENT):
          section = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, isPdf ? /*#__PURE__*/_react.default.createElement("iframe", {
            src: `https://docs.google.com/gview?url=${src}&embedded=true`,
            title: "file",
            width: "100%",
            height: "200",
            loading: "eager"
          }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Box, {
            className: classes.documentFile
          }, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
            className: classes.downloadButton,
            onClick: () => window.open(src, '_blank')
          }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "download")), /*#__PURE__*/_react.default.createElement(_material.Typography, {
            sx: {
              marginLeft: '5px'
            }
          }, m.file.filename)), /*#__PURE__*/_react.default.createElement(_material.Typography, {
            component: 'span'
          }, bytesToSize(m.file.filesize))));
          break;

        default:
          section = /*#__PURE__*/_react.default.createElement(_Icon.default, null, "hide_image");
          break;
      }
    }

    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, section);
  };
  /**
   * Renders snippet or thread type message object
   */


  const c = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, snippetType ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.ListItem, null, /*#__PURE__*/_react.default.createElement(_material.ListItemAvatar, null, scUserContext['user'] && scUserContext['user'].username === message.receiver.username ? /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    alt: message.sender.username,
    src: message.sender.avatar
  }) : /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    alt: message.receiver.username,
    src: message.receiver.avatar
  })), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
    primary: /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.info
    }, scUserContext['user'] && scUserContext['user'].username === message.receiver.username ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span"
    }, message.sender.username) : /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span"
    }, message.receiver.username), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span"
    }, `${intl.formatDate(message.last_message_at, {
      weekday: 'long',
      day: 'numeric'
    })}`)),
    secondary: /*#__PURE__*/_react.default.createElement(_material.Box, {
      component: "span",
      className: classes.info
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span",
      dangerouslySetInnerHTML: {
        __html: message.headline
      }
    }), isNew && /*#__PURE__*/_react.default.createElement(_Icon.default, {
      fontSize: "small",
      className: classes.unread
    }, "fiber_manual_record"))
  }))) : /*#__PURE__*/_react.default.createElement(_reactLazyload.default, {
    once: true
  }, /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    onMouseEnter: onMouseEnter,
    onMouseLeave: onMouseLeave,
    button: true
  }, !snippetType && isHovering && loggedUser === message.sender.id && message.status !== 'hidden' && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    sx: {
      marginBottom: '25px'
    },
    onClick: onDeleteIconClick
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "delete"))), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
    primary: /*#__PURE__*/_react.default.createElement(_material.Box, {
      className: classes.messageBox
    }, hasFile ? renderMessageFile(message) : /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span",
      dangerouslySetInnerHTML: {
        __html: message.message
      }
    })),
    secondary: /*#__PURE__*/_react.default.createElement(_material.Box, {
      component: "span",
      className: classes.messageTime
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span"
    }, `${intl.formatDate(message.created_at, {
      hour: 'numeric',
      minute: 'numeric'
    })}`))
  }))));
  /**
   * Renders root object (if not hidden by autoHide prop)
   */


  if (!autoHide) {
    return /*#__PURE__*/_react.default.createElement(Root, _extends({
      className: (0, _classnames.default)(classes.root, className)
    }, rest), /*#__PURE__*/_react.default.createElement(_List.default, null, c));
  }

  return null;
}