"use strict";

exports.__esModule = true;
exports.default = BroadcastMessages;

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

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

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

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

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

var _Message = _interopRequireDefault(require("./Message"));

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

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

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

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

var _pubsubJs = _interopRequireDefault(require("pubsub-js"));

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

const _excluded = ["id", "className", "MessageProps", "subscriptionChannel"];

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 = 'SCBroadcastMessages';
const classes = {
  root: `${PREFIX}-root`,
  boxLoadMore: `${PREFIX}-box-load-more`,
  buttonLoadMore: `${PREFIX}-button-load-more`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  [`& .${classes.boxLoadMore}`]: {
    '& > div': {
      paddingBottom: theme.spacing(2)
    },
    marginBottom: theme.spacing(2)
  },
  [`& .${classes.buttonLoadMore}`]: {
    textTransform: 'capitalize',
    marginLeft: -10
  }
}));

/**
 > API documentation for the Community-UI Broadcast Messages component. Learn about the available props and the CSS API.
 > This component handles message broadcasts. It initially displays unseen messages. If all messages have been viewed it will show at most one message.
 *
 #### Import
 ```jsx
 import {BroadcastMessages} from '@selfcommunity/ui';
 ```
 #### Component Name
 The name `SCBroadcastMessages` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCBroadcastMessages-root|Styles applied to the root element.|
 |boxLoadMore|.SCBroadcastMessages-box-load-more|Styles applied to load more box.|
 |buttonLoadMore|.SCBroadcastMessages-button-load-more|Styles applied to load more button.|

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

  const {
    id = 'broadcast_messages',
    className = null,
    MessageProps = {},
    subscriptionChannel = `${_core.SCNotificationTopicType.INTERACTION}.${_core.SCNotificationTypologyType.NOTIFICATION_BANNER}`
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const broadcastMessagesRefreshUrl = `${_core.Endpoints.BroadcastMessagesList.url()}?limit=3`;
  const [loading, setLoading] = (0, _react.useState)(null);
  const [next, setNext] = (0, _react.useState)(broadcastMessagesRefreshUrl);
  const [messages, setMessages] = (0, _react.useState)([]);
  const [viewAll, setViewAll] = (0, _react.useState)(false); // CONTEXT

  const scUserContext = (0, _core.useSCUser)(); // CONST

  const authUserId = scUserContext.user ? scUserContext.user.id : null;
  const unViewedMessages = messages.filter(m => !m.viewed_at);
  const viewedMessageCounter = messages.length - unViewedMessages.length; // REFS

  const refreshSubscription = (0, _react.useRef)(null);

  const handleDisposeMessage = message => {
    setMessages(messages.filter(m => m.id != message.id));

    if (messages.length <= 1) {
      fetchMessages(true);
    }
  };
  /**
   * Fetch broadcast messages
   * Loads until the messages are already seen
   */


  const performFetchMessages = async next => {
    const response = await _core.http.request({
      url: next,
      method: _core.Endpoints.BroadcastMessagesList.method
    });
    const data = response.data;

    if (data.next && !data.results[data.results.length - 1]['viewed_at']) {
      return {
        data: data.results.concat((await performFetchMessages(data.next)).data),
        next: data.next
      };
    }

    return {
      data: data.results,
      next: data.next
    };
  };
  /**
   * Fetch broadcast messages
   */


  const fetchMessages = (refresh = false) => {
    setLoading(true);
    performFetchMessages(refresh ? broadcastMessagesRefreshUrl : next).then(res => {
      setMessages(refresh ? res.data : [...messages, ...res.data]);
      setNext(res.next);
      setLoading(false);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  };
  /**
   * if messages.length < unViewedMessages.length show other message
   * if the difference between the 2 arrays is small fetch remote messages
   */


  const fetchOtherMessages = () => {
    setViewAll(true);

    if (next && viewAll || next && !viewAll && viewedMessageCounter <= 2) {
      fetchMessages();
    }
  };
  /**
   * On mount, fetch first page of notifications
   */


  (0, _react.useEffect)(() => {
    if (authUserId !== null) {
      fetchMessages();
    }
  }, [authUserId]);
  /**
   * Notification subscriber
   */

  const subscriber = (msg, data) => {
    fetchMessages(true);
  };
  /**
   * When a ws notification arrives, update data
   */


  (0, _react.useEffect)(() => {
    refreshSubscription.current = _pubsubJs.default.subscribe(subscriptionChannel, subscriber);
    return () => {
      _pubsubJs.default.unsubscribe(refreshSubscription.current);
    };
  }, []);
  const messagesToShow = [...unViewedMessages, ...messages.slice(unViewedMessages.length, viewAll ? viewedMessageCounter : 1)];
  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    id: id,
    className: (0, _classnames.default)(classes.root, className)
  }, rest), messagesToShow.map((message, index) => /*#__PURE__*/_react.default.createElement(_material.Box, {
    key: index
  }, /*#__PURE__*/_react.default.createElement(_Message.default, _extends({
    message: message
  }, MessageProps, {
    onClose: handleDisposeMessage
  })))), loading && /*#__PURE__*/_react.default.createElement(_Skeleton.MessageSkeleton, null), loading !== null && !loading && (next || viewedMessageCounter > 0 && !viewAll) && /*#__PURE__*/_react.default.createElement(_Widget.default, {
    className: classes.boxLoadMore
  }, /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
    variant: "text",
    onClick: fetchOtherMessages,
    disabled: loading,
    color: "inherit",
    classes: {
      root: classes.buttonLoadMore
    }
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.broadcastMessages.loadMore",
    defaultMessage: "ui.broadcastMessages.loadMore"
  })))));
}