"use strict";

exports.__esModule = true;
exports.default = SnippetNotifications;

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

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

var _Comment = _interopRequireDefault(require("../Notification/Comment"));

var _UserFollow = _interopRequireDefault(require("../Notification/UserFollow"));

var _UndeletedFor = _interopRequireDefault(require("../Notification/UndeletedFor"));

var _DeletedFor = _interopRequireDefault(require("../Notification/DeletedFor"));

var _UserConnection = _interopRequireDefault(require("../Notification/UserConnection"));

var _PrivateMessage = _interopRequireDefault(require("../Notification/PrivateMessage"));

var _UserBlocked = _interopRequireDefault(require("../Notification/UserBlocked"));

var _Mention = _interopRequireDefault(require("../Notification/Mention"));

var _CollapsedFor = _interopRequireDefault(require("../Notification/CollapsedFor"));

var _KindlyNoticeFor = _interopRequireDefault(require("../Notification/KindlyNoticeFor"));

var _KindlyNoticeFlag = _interopRequireDefault(require("../Notification/KindlyNoticeFlag"));

var _VoteUp = _interopRequireDefault(require("../Notification/VoteUp"));

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

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

var _ContributionFollow = _interopRequireDefault(require("../Notification/ContributionFollow"));

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

var _IncubatorApproved = _interopRequireDefault(require("../Notification/IncubatorApproved"));

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

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

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

var _ScrollContainer = _interopRequireDefault(require("../../shared/ScrollContainer"));

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

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

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

const _excluded = ["id", "className", "showMax", "handleCustomNotification", "handleNotification", "ScrollContainerProps", "onNotificationClick"];

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 = 'SCSnippetNotifications';
const classes = {
  root: `${PREFIX}-root`,
  notificationsWrap: `${PREFIX}-notifications-wrap`,
  emptyBoxNotifications: `${PREFIX}-empty-box-notifications`,
  notificationsList: `${PREFIX}-notifications-list`,
  notificationItem: `${PREFIX}-notification-item`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  width: '100%',
  [`& .${classes.notificationsWrap}`]: {
    height: 330,
    maxWidth: 320,
    overflowY: 'hidden'
  },
  [`& .${classes.notificationItem}`]: {
    padding: 0,
    margin: `${theme.spacing()} 0px`,
    whiteSpace: 'normal',
    '&:hover': {
      backgroundColor: 'rgba(0, 0, 0, 0.05)',
      cursor: 'default'
    }
  },
  '& a': {
    textDecoration: 'none',
    color: theme.palette.text.primary
  }
}));

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

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCSnippetNotification-root|Styles applied to the root element.|
 |notificationsWrap|.SCSnippetNotification-notification-wrap|Styles applied to the notifications wrap.|
 |emptyBoxNotifications|.SCSnippetNotification-empty-box-notifications|Styles applied to the box indicating that there are no notifications.|
 |notificationsList|.SCSnippetNotification-notifications-list|Styles applied to the list of notifications.|
 |notificationItem|.SCSnippetNotification-notification-item|Styles applied to the single notification.|

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

  const {
    id = `snippetNotifications`,
    className,
    showMax = 20,
    handleCustomNotification,
    handleNotification,
    ScrollContainerProps = {},
    onNotificationClick
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


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

  const [notifications, setNotifications] = (0, _react.useState)([]);
  const [loading, setLoading] = (0, _react.useState)(true); // REFS

  const notificationSubscription = (0, _react.useRef)(null);
  /**
   * Perform vote
   */

  const performFetchNotifications = (0, _react.useMemo)(() => () => {
    return _core.http.request({
      url: _core.Endpoints.UserNotificationList.url(),
      method: _core.Endpoints.UserNotificationList.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      return Promise.resolve(res.data);
    });
  }, []);
  /**
   * Handles vote
   * @param comment
   */

  function fetchNotifications() {
    setLoading(true);
    performFetchNotifications().then(data => {
      setNotifications(data.results);
      setLoading(false);
      scUserContext.refreshNotificationCounters();
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  }
  /**
   * Fetch notifications
   */


  (0, _react.useEffect)(() => {
    if (scUserContext.user && loading) {
      fetchNotifications();
    }
  }, [scUserContext.user]);
  /**
   * Notification subscriber
   * @param msg
   * @param data
   */

  const notificationSubscriber = (msg, data) => {
    /**
     * Ignore notifications of type: notification_banner
     * (data.data.activity_type === SCNotificationTypologyType.NOTIFICATION_BANNER)
     */
    if (data && data.type === _core.SCNotificationTopicType.INTERACTION && _core.SCNotification.SCNotificationMapping[data.data.activity_type] && !_core.SCNotification.SCSilentSnippetNotifications.includes(data.data.activity_type)) {
      if (data.data.notification_obj) {
        setNotifications([...[{
          is_new: true,
          sid: '',
          aggregated: [data.data.notification_obj]
        }], ...notifications]);
      }
    }
  };

  const handleSingleNotificationClick = (e, n) => {
    if (onNotificationClick) {
      onNotificationClick(e, n);
    }
  };
  /**
   * On mount, fetches first page of notifications
   * On mount, subscribe to receive notification updates
   */


  (0, _react.useEffect)(() => {
    if (!loading) {
      notificationSubscription.current = _pubsubJs.default.subscribe(_core.SCNotificationTopicType.INTERACTION, notificationSubscriber);
    }

    return () => {
      notificationSubscription.current && _pubsubJs.default.unsubscribe(notificationSubscription.current);
    };
  }, [loading]);
  /**
   * Render every single notification in aggregated group
   * @param n
   * @param i
   */

  function renderAggregatedItem(n, i) {
    const type = n.type;
    let content;

    if (type === _core.SCNotificationTypologyType.COMMENT || type === _core.SCNotificationTypologyType.NESTED_COMMENT) {
      content = /*#__PURE__*/_react.default.createElement(_Comment.default, {
        notificationObject: n,
        key: i,
        index: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.FOLLOW) {
      content = /*#__PURE__*/_react.default.createElement(_ContributionFollow.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.USER_FOLLOW) {
      content = /*#__PURE__*/_react.default.createElement(_UserFollow.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.CONNECTION_REQUEST || type === _core.SCNotificationTypologyType.CONNECTION_ACCEPT) {
      content = /*#__PURE__*/_react.default.createElement(_UserConnection.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.VOTE_UP) {
      content = /*#__PURE__*/_react.default.createElement(_VoteUp.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.KINDLY_NOTICE_ADVERTISING || type === _core.SCNotificationTypologyType.KINDLY_NOTICE_AGGRESSIVE || type === _core.SCNotificationTypologyType.KINDLY_NOTICE_POOR || type === _core.SCNotificationTypologyType.KINDLY_NOTICE_VULGAR || type === _core.SCNotificationTypologyType.KINDLY_NOTICE_OFFTOPIC) {
      content = /*#__PURE__*/_react.default.createElement(_KindlyNoticeFor.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.KINDLY_NOTICE_FLAG) {
      content = /*#__PURE__*/_react.default.createElement(_KindlyNoticeFlag.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.DELETED_FOR_ADVERTISING || type === _core.SCNotificationTypologyType.DELETED_FOR_AGGRESSIVE || type === _core.SCNotificationTypologyType.DELETED_FOR_POOR || type === _core.SCNotificationTypologyType.DELETED_FOR_VULGAR || type === _core.SCNotificationTypologyType.DELETED_FOR_OFFTOPIC) {
      content = /*#__PURE__*/_react.default.createElement(_DeletedFor.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.UNDELETED_FOR) {
      content = /*#__PURE__*/_react.default.createElement(_UndeletedFor.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.COLLAPSED_FOR_ADVERTISING || type === _core.SCNotificationTypologyType.COLLAPSED_FOR_AGGRESSIVE || type === _core.SCNotificationTypologyType.COLLAPSED_FOR_POOR || type === _core.SCNotificationTypologyType.COLLAPSED_FOR_VULGAR || type === _core.SCNotificationTypologyType.COLLAPSED_FOR_OFFTOPIC) {
      content = /*#__PURE__*/_react.default.createElement(_CollapsedFor.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.PRIVATE_MESSAGE) {
      content = /*#__PURE__*/_react.default.createElement(_PrivateMessage.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.BLOCKED_USER || type === _core.SCNotificationTypologyType.UNBLOCKED_USER) {
      content = /*#__PURE__*/_react.default.createElement(_UserBlocked.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.MENTION) {
      content = /*#__PURE__*/_react.default.createElement(_Mention.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.INCUBATOR_APPROVED) {
      content = /*#__PURE__*/_react.default.createElement(_IncubatorApproved.default, {
        notificationObject: n,
        key: i,
        template: _types.SCNotificationObjectTemplateType.SNIPPET
      });
    } else if (type === _core.SCNotificationTypologyType.CUSTOM_NOTIFICATION && handleCustomNotification) {
      content = handleCustomNotification(n);
    }

    if (type && handleNotification) {
      /** Override content */
      content = handleNotification(type, n, content);
    }

    return content;
  }
  /**
   * Renders root object
   */


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    id: id,
    className: (0, _classnames.default)(classes.root, className)
  }, rest), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.notificationsWrap
  }, loading ? /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
    elevation: 0
  }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, notifications.length === 0 ? /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.emptyBoxNotifications
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.snippetNotifications.noNotifications",
    defaultMessage: "ui.snippetNotifications.noNotifications"
  })) : /*#__PURE__*/_react.default.createElement(_ScrollContainer.default, ScrollContainerProps, /*#__PURE__*/_react.default.createElement(_material.MenuList, {
    className: classes.notificationsList
  }, notifications.slice(0, showMax).map((notificationObject, i) => notificationObject.aggregated.map((n, k) => /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    className: classes.notificationItem,
    key: k,
    onClick: e => handleSingleNotificationClick(e, n)
  }, renderAggregatedItem(n, i)))))))));
}