"use strict";

exports.__esModule = true;
exports.default = Snippets;

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

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

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

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

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

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

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

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

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

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

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

const _excluded = ["autoHide", "className", "onSnippetClick", "threadId", "getSnippetHeadline", "shouldUpdate"];

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 = 'SCSnippets';
const classes = {
  root: `${PREFIX}-root`,
  selected: `${PREFIX}-selected`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  width: '500px',
  ['& .MuiCardContent-root']: {
    '&:last-child': {
      paddingBottom: 0
    }
  },
  [`& .${classes.selected}`]: {
    background: theme.palette.grey['A200']
  }
}));

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

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCSnippets-root|Styles applied to the root element.|
 |selected|.SCSnippets-selected|Styles applied to the selected element.|

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

  const {
    autoHide = false,
    className = null,
    onSnippetClick,
    threadId,
    getSnippetHeadline,
    shouldUpdate
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const [snippets, setSnippets] = (0, _react.useState)([]);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [total, setTotal] = (0, _react.useState)(0); // REFS

  const refreshSubscription = (0, _react.useRef)(null);
  /**
   * Fetches Snippets
   */

  function fetchSnippets() {
    _core.http.request({
      url: _core.Endpoints.GetSnippets.url(),
      method: _core.Endpoints.GetSnippets.method
    }).then(res => {
      const data = res.data;
      setSnippets(data.results);
      setLoading(false);
      setTotal(data.count);
    }).catch(error => {
      console.log(error);
    });
  }
  /**
   * Updates snippet headline and status
   * @param id
   * @param headline
   * @param status
   */


  function updateSnippets(id, headline, status) {
    const newSnippets = [...snippets];
    const index = newSnippets.findIndex(s => s.id === id);

    if (index !== -1) {
      newSnippets[index].headline = headline;
      newSnippets[index].thread_status = status;
      setSnippets(newSnippets);
    }
  }
  /**
   * Updates snippet status
   * @param id
   * @param status
   */


  function updateStatus(id, status) {
    const newSnippets = [...snippets];
    const index = newSnippets.findIndex(s => s.id === id);

    if (index !== -1) {
      newSnippets[index].thread_status = status;
      setSnippets(newSnippets);
    }
  }
  /**
   * On mount, fetches snippets
   */


  (0, _react.useEffect)(() => {
    fetchSnippets();
  }, [shouldUpdate]);
  /**
   * When a ws notification arrives, updates data
   */

  (0, _react.useEffect)(() => {
    refreshSubscription.current = _pubsubJs.default.subscribe(`${_core.SCNotificationTopicType.INTERACTION}.${_core.SCNotificationTypologyType.PRIVATE_MESSAGE}`, subscriber);
    return () => {
      _pubsubJs.default.unsubscribe(refreshSubscription.current);
    };
  }, [snippets]);
  /**
   * When the logged in user sends a message, snippet headline is updated
   */

  (0, _react.useEffect)(() => {
    if (threadId) {
      updateSnippets(threadId, getSnippetHeadline, null);
    }
  }, [getSnippetHeadline]);
  /**
   * Notification subscriber
   */

  const subscriber = (msg, data) => {
    const res = data.data;
    updateSnippets(res.thread_id, res.notification_obj.snippet.headline, res.notification_obj.snippet.thread_status);
  };
  /**
   * Handles thread opening
   */


  function handleOpenThread(msg) {
    onSnippetClick(msg);
    updateStatus(msg.id, null);
  }
  /**
   * Renders snippets list
   */


  const c = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, loading ? /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
    elevation: 0
  }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.categoriesSuggestion.noResults",
    defaultMessage: "ui.categoriesSuggestion.noResults"
  })) : /*#__PURE__*/_react.default.createElement(_material.List, null, snippets.map((message, index) => /*#__PURE__*/_react.default.createElement("div", {
    key: index
  }, /*#__PURE__*/_react.default.createElement(_Message.default, {
    elevation: 0,
    message: message,
    key: message.id,
    onClick: () => handleOpenThread(message),
    className: message.id === threadId ? classes.selected : ''
  }), index < total - 1 ? /*#__PURE__*/_react.default.createElement(_material.Divider, null) : null)))));
  /**
   * Renders the component (if not hidden by autoHide prop)
   */


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

  return null;
}