"use strict";

exports.__esModule = true;
exports.default = UsersFollowed;

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

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

var _List = _interopRequireDefault(require("@mui/material/List"));

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

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

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 _Errors = require("../../constants/Errors");

var _BaseDialog = _interopRequireDefault(require("../../shared/BaseDialog"));

var _CentralProgress = _interopRequireDefault(require("../../shared/CentralProgress"));

var _reactInfiniteScrollComponent = _interopRequireDefault(require("react-infinite-scroll-component"));

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

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); }

const messages = (0, _reactIntl.defineMessages)({
  title: {
    id: 'ui.usersFollowed.title',
    defaultMessage: 'ui.usersFollowed.title'
  },
  noUsers: {
    id: 'ui.usersFollowed.subtitle.noResults',
    defaultMessage: 'ui.usersFollowed.subtitle.noResults'
  }
});
const PREFIX = 'SCUsersFollowed';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  followedItem: `${PREFIX}-followed-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.followedItem}`]: {
    marginBottom: theme.spacing()
  }
}));

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

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCUsersFollowed-root|Styles applied to the root element.|
 |title|.SCUsersFollowed-title|Styles applied to the title element.|
 |noResults|.SCUsersFollowed-no-results|Styles applied to no results section.|
 |followedItem|.SCUsersFollowed-followed-item|Styles applied to the followed item element.|
 |showMore|.SCUsersFollowed-show-more|Styles applied to show more button element.|

 * @param inProps
 */
function UsersFollowed(inProps) {
  // CONST
  const limit = 3; // INTL

  const intl = (0, _reactIntl.useIntl)(); // CONTEXT

  const scUserContext = (0, _react.useContext)(_core.SCUserContext);
  const scPreferencesContext = (0, _react.useContext)(_core.SCPreferencesContext);
  const contentAvailability = _core.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences && scPreferencesContext.preferences[_core.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value; // PROPS

  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });
  const {
    userId,
    autoHide,
    className,
    UserProps = {}
  } = props; // STATE

  const [followed, setFollowed] = (0, _react.useState)([]);
  const [visibleUsers, setVisibleUsers] = (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 [openUsersFollowedDialog, setOpenUsersFollowedDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.UsersFollowed.url({
    id: userId != null ? userId : scUserContext.user['id']
  })}?limit=10`);
  /**
   * Handles list change on user follow
   */

  function handleOnFollowUser(user, follow) {
    if (scUserContext.user['id'] === userId) {
      setFollowed(followed.filter(u => u.id !== user.id));
      setTotal(prev => prev - 1);

      if (visibleUsers < limit && total > 1) {
        loadUsers(1);
      }
    }
  }
  /**
   * Fetches the list of users followed
   */


  function fetchFollowed() {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.UsersFollowed.method
      }).then(res => {
        const data = res.data;
        setFollowed([...followed, ...data.results]);
        setHasMore(data.count > visibleUsers);
        setNext(data['next']);
        setLoading(false);
        setTotal(data.count);
      }).catch(error => {
        setLoading(false);

        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * Loads more users when followed list changes
   */


  function loadUsers(n) {
    const newIndex = visibleUsers + n;
    const newHasMore = newIndex < followed.length - 1;
    setVisibleUsers(newIndex);
    setHasMore(newHasMore);
  }
  /**
   * On mount, fetches the list of users followed
   */


  (0, _react.useEffect)(() => {
    if (!contentAvailability && !scUserContext.user) {
      return;
    }

    fetchFollowed();
  }, [scUserContext.user]);
  /**
   * Renders the list of users followed
   */

  const u = /*#__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"
  }, `${intl.formatMessage(messages.title, {
    total: total
  })}`), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, `${intl.formatMessage(messages.noUsers)}`) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_List.default, null, followed.slice(0, visibleUsers).map(user => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: user.id
  }, /*#__PURE__*/_react.default.createElement(_User.default, _extends({
    elevation: 0,
    user: user,
    followConnectUserButtonProps: {
      onFollow: handleOnFollowUser
    },
    className: classes.followedItem
  }, UserProps))))), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    className: classes.showMore,
    onClick: () => setOpenUsersFollowedDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.usersFollowed.button.showAll",
    defaultMessage: "ui.usersFollowed.button.showAll"
  })), openUsersFollowedDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: `${intl.formatMessage(messages.title, {
      total: total
    })}`,
    onClose: () => setOpenUsersFollowedDialog(false),
    open: openUsersFollowedDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: followed.length,
    next: fetchFollowed,
    hasMore: Boolean(next),
    loader: /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
      size: 30
    }),
    height: 400,
    endMessage: /*#__PURE__*/_react.default.createElement("p", {
      style: {
        textAlign: 'center'
      }
    }, /*#__PURE__*/_react.default.createElement("b", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.usersFollowed.noMoreResults",
      defaultMessage: "ui.usersFollowed.noMoreResults"
    })))
  }, /*#__PURE__*/_react.default.createElement(_List.default, null, followed.map(f => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: f.id
  }, /*#__PURE__*/_react.default.createElement(_User.default, _extends({
    elevation: 0,
    user: f
  }, UserProps, {
    className: classes.followedItem,
    followConnectUserButtonProps: {
      onFollow: handleOnFollowUser
    }
  }))))))))));
  /**
   * if there are no results and autoHide prop is set to true ,component is hidden
   */


  if (autoHide && !total) {
    return null;
  }
  /**
   * If content availability community option is false and user is anonymous , component is hidden.
   */


  if (!contentAvailability && !scUserContext.user) {
    return null;
  }
  /**
   * Renders root object
   */


  return /*#__PURE__*/_react.default.createElement(Root, {
    className: (0, _classnames.default)(classes.root, className)
  }, u);
}