"use strict";

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

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

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

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

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

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

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

var _MarkRead = _interopRequireDefault(require("../../shared/MarkRead"));

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

var _types = require("../../types");

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

var _colors = require("@mui/material/colors");

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

const _excluded = ["id", "className", "message", "onClose", "onRead", "template"];

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 = 'SCBroadcastMessage';
const classes = {
  header: `${PREFIX}-header`,
  title: `${PREFIX}-title`,
  media: `${PREFIX}-media`,
  content: `${PREFIX}-content`,
  listItemSnippet: `${PREFIX}-list-item-snippet`,
  listItemSnippetNew: `${PREFIX}-list-item-snippet-new`,
  messageIconWrap: `${PREFIX}-flag-icon-wrap`,
  messageIconSnippet: `${PREFIX}-flag-icon-snippet`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  width: '100%',
  marginBottom: theme.spacing(2),
  [`& .${classes.header} .MuiAvatar-img`]: {
    objectFit: 'fill'
  },
  [`& .${classes.title}`]: {
    padding: '4px 16px'
  },
  [`& .${classes.listItemSnippet}`]: {
    padding: '0px 5px',
    alignItems: 'center'
  },
  [`& .${classes.listItemSnippetNew}`]: {
    borderLeft: '2px solid red'
  },
  [`& .${classes.messageIconWrap}`]: {
    minWidth: 'auto',
    paddingRight: 10
  },
  [`& .${classes.messageIconSnippet}`]: {
    backgroundColor: _colors.red[500],
    color: '#FFF',
    width: 30,
    height: 30
  }
}));
const PREFERENCES = [_core.SCPreferences.LOGO_NAVBAR_LOGO, _core.SCPreferences.TEXT_APPLICATION_NAME];

function Message(props) {
  // PROPS
  const {
    id = `message_${props.message.id}`,
    className,
    message,
    onClose = null,
    onRead = null,
    template = _types.SCBroadcastMessageTemplateType.DETAIL
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const [open, setOpen] = (0, _react.useState)(message.disposed_at === null);
  const [closing, setClosing] = (0, _react.useState)(false); // CONTEXT

  const scPrefernces = (0, _react.useContext)(_core.SCPreferencesContext); // ROUTING

  const scRoutingContext = (0, _core.useSCRouting)(); // Compute preferences

  const preferences = (0, _react.useMemo)(() => {
    const _preferences = {};
    PREFERENCES.map(p => _preferences[p] = p in scPrefernces.preferences ? scPrefernces.preferences[p].value : null);
    return _preferences;
  }, [scPrefernces.preferences]); // HANDLERS

  const handleClose = () => {
    setClosing(true);

    _core.http.request({
      url: _core.Endpoints.BroadcastMessagesDispose.url(),
      method: _core.Endpoints.BroadcastMessagesDispose.method,
      data: {
        banner_ids: [message.id]
      }
    }).then(() => {
      setOpen(false);
      setClosing(false);
      onClose && onClose(message);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  }; // RENDER


  const renderContent = banner => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.CardContent, {
      className: classes.title
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "h6"
    }, banner.title)), banner.image && /*#__PURE__*/_react.default.createElement(_material.CardMedia, {
      className: classes.media,
      component: "img",
      image: banner.image,
      alt: banner.title
    }), /*#__PURE__*/_react.default.createElement(_material.CardContent, {
      className: classes.content
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "body2",
      color: "text.secondary"
    }, banner.body_text), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      variant: "body2",
      color: "text.secondary"
    }, /*#__PURE__*/_react.default.createElement(_core.Link, {
      to: banner.link,
      target: banner.open_in_new_tab ? '_blank' : '_self'
    }, banner.link_text))));
  }; // Banner


  const {
    banner
  } = message;

  if (template === _types.SCBroadcastMessageTemplateType.DETAIL || _types.SCBroadcastMessageTemplateType.TOAST) {
    /**
     * With a fade in transition show the Card (Widget)
     * Include also MarkRead component to
     */
    return /*#__PURE__*/_react.default.createElement(Root, _extends({
      id: id,
      className: className
    }, rest), /*#__PURE__*/_react.default.createElement(_material.Fade, {
      in: open,
      unmountOnExit: true
    }, /*#__PURE__*/_react.default.createElement(_material.Box, null, message.viewed_at === null && /*#__PURE__*/_react.default.createElement(_MarkRead.default, {
      endpoint: _core.Endpoints.BroadcastMessagesMarkRead,
      data: {
        banner_ids: [message.id]
      }
    }), /*#__PURE__*/_react.default.createElement(_material.CardHeader, {
      className: classes.header,
      avatar: /*#__PURE__*/_react.default.createElement(_material.Avatar, {
        alt: preferences[_core.SCPreferences.TEXT_APPLICATION_NAME],
        src: preferences[_core.SCPreferences.LOGO_NAVBAR_LOGO]
      }),
      action: template === _types.SCBroadcastMessageTemplateType.DETAIL && /*#__PURE__*/_react.default.createElement(_material.IconButton, {
        "aria-label": "close",
        onClick: handleClose,
        disabled: closing
      }, closing ? /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
        size: 20
      }) : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "close")),
      title: /*#__PURE__*/_react.default.createElement(_material.Chip, {
        color: "secondary",
        size: "small",
        label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
          id: "ui.broadcastMessages.message.chip",
          defaultMessage: "ui.broadcastMessages.message.chip"
        })
      })
    }), renderContent(banner))));
  } // SCBroadcastMessageTemplateType.SNIPPET


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    id: id,
    className: className
  }, rest), /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    alignItems: 'center',
    component: 'div',
    classes: {
      root: (0, _classnames.default)(classes.listItemSnippet, classes.listItemSnippetNew)
    }
  }, /*#__PURE__*/_react.default.createElement(_material.ListItemAvatar, {
    classes: {
      root: classes.messageIconWrap
    }
  }, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    variant: "circular",
    classes: {
      root: classes.messageIconSnippet
    }
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "info"))), /*#__PURE__*/_react.default.createElement(_material.ListItemText, {
    disableTypography: true,
    primary: /*#__PURE__*/_react.default.createElement(_core.Link, {
      to: scRoutingContext.url(_core.SCRoutes.USER_NOTIFICATIONS_ROUTE_NAME, {})
    }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: "span",
      color: "inherit"
    }, banner.title))
  })));
}