"use strict";

exports.__esModule = true;
exports.default = CategoriesPopular;

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

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

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

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

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

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

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

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 = 'SCCategoriesPopular';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  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)
}));
/**
 > API documentation for the Community-UI Categories Popular component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {CategoriesPopular} from '@selfcommunity/ui';
 ```

 #### Component Name
 The name `SCCategoriesPopular` can be used when providing style overrides in the theme.

 #### CSS

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

 * @param inProps
 */

function CategoriesPopular(inProps) {
  // CONST
  const limit = 3; // PROPS

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

  const {
    autoHide = true,
    className,
    CategoryProps = {}
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // 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 [openPopularCategoriesDialog, setOpenPopularCategoriesDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.PopularCategories.url()}?limit=10`);
  /**
   * Fetches popular categories list
   */

  const fetchPopularCategories = (0, _react.useMemo)(() => () => {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.PopularCategories.method
      }).then(res => {
        if (res.status < 300) {
          const data = res.data;
          setCategories([...categories, ...data['results']]);
          setHasMore(data['count'] > visibleCategories);
          setNext(data['next']);
          setLoading(false);
          setTotal(data['count']);
        }
      }).catch(error => {
        setLoading(false);

        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }, [categories, next, loading]);
  /**
   * On mount, fetches popular categories list
   */

  (0, _react.useEffect)(() => {
    fetchPopularCategories();
  }, []);
  /**
   * Renders popular categories list
   */

  const c = /*#__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.categoriesPopular.title",
    defaultMessage: "ui.categoriesPopular.title"
  })), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.categoriesPopular.noResults",
    defaultMessage: "ui.categoriesPopular.noResults"
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.List, null, categories.slice(0, visibleCategories).map(category => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: category.id
  }, /*#__PURE__*/_react.default.createElement(_Category.default, _extends({
    elevation: 0,
    category: category
  }, CategoryProps))))), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    className: classes.showMore,
    onClick: () => setOpenPopularCategoriesDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.categoriesPopular.button.showAll",
    defaultMessage: "ui.categoriesPopular.button.showAll"
  }))), openPopularCategoriesDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.categoriesPopular.title",
      id: "ui.categoriesPopular.title"
    }),
    onClose: () => setOpenPopularCategoriesDialog(false),
    open: openPopularCategoriesDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: categories.length,
    next: fetchPopularCategories,
    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.categoriesPopular.noMoreResults",
      defaultMessage: "ui.categoriesPopular.noMoreResults"
    })))
  }, /*#__PURE__*/_react.default.createElement(_material.List, null, categories.map(c => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: c.id
  }, /*#__PURE__*/_react.default.createElement(_Category.default, _extends({
    elevation: 0,
    category: c
  }, CategoryProps)))))))));
  /**
   * Renders root object (if results and autoHide prop is set to false, otherwise component is hidden)
   */


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

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