"use strict";

exports.__esModule = true;
exports.default = CategoriesFollowed;

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

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

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

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

var _Card = _interopRequireDefault(require("@mui/material/Card"));

var _CardContent = _interopRequireDefault(require("@mui/material/CardContent"));

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

var _Category = _interopRequireDefault(require("../Category"));

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

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

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

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

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

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

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

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)({
  categoriesFollowed: {
    id: 'ui.categoriesFollowed.categoriesFollowed',
    defaultMessage: 'ui.categoriesFollowed.categoriesFollowed'
  },
  noCategories: {
    id: 'ui.categoriesFollowed.subtitle.noResults',
    defaultMessage: 'ui.categoriesFollowed.subtitle.noResults'
  }
});
const PREFIX = 'SCCategoriesFollowed';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  noResults: `${PREFIX}-noResults`
};
const Root = (0, _styles.styled)(_Card.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  maxWidth: 700,
  marginBottom: theme.spacing(2)
}));
/**
 > API documentation for the Community-UI Categories Followed component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {CategoriesFollowed} from '@selfcommunity/ui';
 ```
 #### Component Name
 The name `SCCategoriesFollowed` can be used when providing style overrides in the theme.

 #### CSS

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

 * @param props
 */

function CategoriesFollowed(props) {
  // CONST
  const limit = 3; // INTL

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

  const scUserContext = (0, _react.useContext)(_core.SCUserContext); // PROPS

  const {
    userId,
    autoHide,
    className,
    CategoryProps = {}
  } = props; // STATE

  const [categories, setCategories] = (0, _react.useState)([]);
  const [visibleCategories, setVisibleCategories] = (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 [openCategoriesFollowedDialog, setOpenCategoriesFollowedDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.FollowedCategories.url({
    id: userId != null ? userId : scUserContext.user['id']
  })}?limit=10`);
  /**
   * Handles list change on category follow
   */

  function handleOnFollowCategory(category, follow) {
    if (scUserContext.user['id'] === userId) {
      setCategories(categories.filter(c => c.id !== category.id));
      setTotal(prev => prev - 1);

      if (visibleCategories < limit && total > 1) {
        loadCategories(1);
      }
    }
  }
  /**
   * fetches Categories Followed
   */


  function fetchCategoriesFollowed() {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.FollowedCategories.method
      }).then(res => {
        const data = res.data;
        setCategories([...categories, ...data]);
        setTotal(data.length);
        setNext(data['next']);
        setHasMore(data.length > visibleCategories);
        setLoading(false);
      }).catch(error => {
        setLoading(false);

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


  function loadCategories(n) {
    const newIndex = visibleCategories + n;
    const newHasMore = newIndex < categories.length - 1;
    setVisibleCategories(newIndex);
    setHasMore(newHasMore);
  }
  /**
   * On mount, fetches the list of categories followed
   */


  (0, _react.useEffect)(() => {
    fetchCategoriesFollowed();
  }, []);
  /**
   * Renders the list of categories followed
   */

  const c = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, loading ? /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
    elevation: 0
  }) : /*#__PURE__*/_react.default.createElement(_CardContent.default, null, !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, `${intl.formatMessage(messages.noCategories)}`) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.title,
    variant: "body1"
  }, `${intl.formatMessage(messages.categoriesFollowed, {
    total: total
  })}`), /*#__PURE__*/_react.default.createElement(_List.default, null, categories.slice(0, visibleCategories).map((category, index) => /*#__PURE__*/_react.default.createElement("div", {
    key: index
  }, /*#__PURE__*/_react.default.createElement(_Category.default, _extends({
    elevation: 0,
    category: category,
    key: category.id,
    followCategoryButtonProps: {
      onFollow: handleOnFollowCategory
    }
  }, CategoryProps))))), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    onClick: () => setOpenCategoriesFollowedDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.categoriesFollowed.button.showAll",
    defaultMessage: "ui.categoriesFollowed.button.showAll"
  }))), openCategoriesFollowedDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.categoriesFollowed.title",
      id: "ui.categoriesFollowed.title"
    }),
    onClose: () => setOpenCategoriesFollowedDialog(false),
    open: openCategoriesFollowedDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: categories.length,
    next: fetchCategoriesFollowed,
    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.categoriesFollowed.noMoreCategories",
      defaultMessage: "ui.categoriesFollowed.noMoreCategories"
    })))
  }, /*#__PURE__*/_react.default.createElement(_List.default, null, categories.map((c, index) => /*#__PURE__*/_react.default.createElement(_Category.default, _extends({
    elevation: 0,
    category: c,
    key: c.id,
    sx: {
      m: 0
    },
    followCategoryButtonProps: {
      onFollow: handleOnFollowCategory
    }
  }, CategoryProps))))))));
  /**
   * Renders root object (if results and if user is logged, otherwise component is hidden)
   */


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

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