"use strict";

exports.__esModule = true;
exports.default = PeopleSuggestion;

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

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

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

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

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

var _User = _interopRequireDefault(require("../User"));

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

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

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

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

const _excluded = ["autoHide", "className", "UserProps"];

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 = 'SCPeopleSuggestion';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  suggestedUserItem: `${PREFIX}-suggested-user-item`,
  noResults: `${PREFIX}-no-results`,
  showMore: `${PREFIX}-show-more`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  marginBottom: theme.spacing(2),
  [`& .${classes.suggestedUserItem}`]: {
    marginBottom: theme.spacing()
  }
}));

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

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCPeopleSuggestion-root|Styles applied to the root element.|
 |title|.SCPeopleSuggestion-title|Styles applied to the title element.|
 |suggestedUserItem|.SCPeopleSuggestion-suggested-user-item|Styles applied to the suggested user element.|
 |noResults|.SCPeopleSuggestion-no-results|Styles applied to the no results section.|
 |showMore|.SCPeopleSuggestion-show-more|Styles applied to show more button element.|

 * @param inProps
 */
function PeopleSuggestion(inProps) {
  // CONST
  const limit = 3; // PROPS

  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    autoHide,
    className,
    UserProps = {}
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const [users, setUsers] = (0, _react.useState)([]);
  const [visiblePeople, setVisiblePeople] = (0, _react.useState)(limit);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [hasMore, setHasMore] = (0, _react.useState)(false);
  const [total, setTotal] = (0, _react.useState)(0);
  const [openPeopleSuggestionDialog, setOpenPeopleSuggestionDialog] = (0, _react.useState)(false); // CONTEXT

  const scUserContext = (0, _react.useContext)(_core.SCUserContext);
  const scPreferencesContext = (0, _react.useContext)(_core.SCPreferencesContext);
  const followEnabled = _core.SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED in scPreferencesContext.preferences && scPreferencesContext.preferences[_core.SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED].value; // CONST

  const authUserId = scUserContext.user ? scUserContext.user.id : null;
  /**
   * Handles list change on user follow
   */

  function handleOnFollowUser(user, follow) {
    setUsers(users.filter(u => u.id !== user.id));
    setTotal(prev => prev - 1);

    if (visiblePeople < limit && total > 1) {
      loadPeople(1);
    }
  }
  /**
   * Handles list change on user connection
   */


  function handleOnConnectUser(user, status) {
    setUsers(users.filter(u => u.id !== user.id));
    setTotal(prev => prev - 1);

    if (visiblePeople < limit && total > 1) {
      loadPeople(1);
    }
  }
  /**
   * Fetches user suggestion list
   */


  function fetchUserSuggestion() {
    _core.http.request({
      url: _core.Endpoints.UserSuggestion.url(),
      method: _core.Endpoints.UserSuggestion.method
    }).then(res => {
      const data = res.data;
      setUsers(data['results']);
      setHasMore(data['count'] > visiblePeople);
      setLoading(false);
      setTotal(data.count);
    }).catch(error => {
      console.log(error);
    });
  }
  /**
   * Loads more people on "see more" button click
   */


  function loadPeople(n) {
    const newIndex = visiblePeople + n;
    const newHasMore = newIndex < users.length - 1;
    setVisiblePeople(newIndex);
    setHasMore(newHasMore);
  }
  /**
   * On mount, fetches people suggestion list
   */


  (0, _react.useEffect)(() => {
    if (scUserContext.user) {
      fetchUserSuggestion();
    }
  }, [authUserId]);
  /**
   * Renders people suggestion list
   */

  const p = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, loading ? /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
    elevation: 0
  }) : /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.title,
    variant: "h5"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.peopleSuggestion.title",
    defaultMessage: "ui.peopleSuggestion.title"
  })), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.peopleSuggestion.subtitle.noResults",
    defaultMessage: "ui.peopleSuggestion.subtitle.noResults"
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.List, null, users.slice(0, visiblePeople).map((user, index) => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: user.id
  }, /*#__PURE__*/_react.default.createElement(_User.default, _extends({
    elevation: 0,
    user: user
  }, followEnabled ? {
    followConnectUserButtonProps: {
      onFollow: handleOnFollowUser
    }
  } : {
    followConnectUserButtonProps: {
      onChangeConnectionStatus: handleOnConnectUser
    }
  }, {
    className: classes.suggestedUserItem
  }, UserProps))))), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    className: classes.showMore,
    size: "small",
    onClick: () => loadPeople(limit)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.peopleSuggestion.button.showMore",
    defaultMessage: "ui.peopleSuggestion.button.showMore"
  }))), openPeopleSuggestionDialog && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null)));
  /**
   * Renders root object (if results and if user is logged, otherwise component is hidden)
   */


  if (autoHide && !total) {
    return null;
  }

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

  return null;
}