"use strict";

exports.__esModule = true;
exports.default = CategoryHeader;

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

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

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

var _FollowCategoryButton = _interopRequireDefault(require("../FollowCategoryButton"));

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

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

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

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

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

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

var _AvatarGroupSkeleton = _interopRequireDefault(require("../Skeleton/AvatarGroupSkeleton"));

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

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

const _excluded = ["className", "categoryId", "category", "FollowCategoryButtonProps", "FollowedByDialogProps"];

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 messages = (0, _reactIntl.defineMessages)({
  followedBy: {
    id: 'ui.categoryHeader.followedBy',
    defaultMessage: 'ui.categoryHeader.followedBy'
  }
});
const PREFIX = 'SCCategoryHeader';
const classes = {
  root: `${PREFIX}-root`,
  cover: `${PREFIX}-cover`,
  name: `${PREFIX}-name`,
  slogan: `${PREFIX}-slogan`,
  info: `${PREFIX}-info`,
  followedCounter: `${PREFIX}-followed-counter`,
  followed: `${PREFIX}-followed`,
  action: `${PREFIX}-action`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  [`& .${classes.cover}`]: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    minHeight: 270,
    color: '#FFF',
    background: 'linear-gradient(180deg, rgba(177,177,177,1) 0%, rgba(255,255,255,1) 90%)'
  },
  [`& .${classes.info}`]: {
    marginTop: theme.spacing(2),
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(2)
  },
  [`& .${classes.name}, & .${classes.slogan}`]: {
    display: 'block',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    textAlign: 'center',
    marginBottom: theme.spacing(2)
  },
  [`& .${classes.followed}, & .${classes.action}`]: {
    textAlign: 'center',
    marginBottom: theme.spacing(2)
  },
  [`& .${classes.followed} .MuiAvatar-root`]: {
    color: '#FFF',
    border: '2px solid #FFF',
    fontSize: 11
  },
  [`& .${classes.followedCounter}`]: {
    display: 'inline'
  }
}));

/**
 *> API documentation for the Community-UI Category Header component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {CategoryHeader} from '@selfcommunity/ui';
 ```
 #### Component Name

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

 * #### CSS
 *
 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCCategoryHeader-root|Styles applied to the root element.|
 |cover|.SCCategoryHeader-cover|Styles applied to the cover element.|
 |name|.SCCategoryHeader-name|Styles applied to the name element.|
 |slogan|.SCCategoryHeader-slogan|Styles applied to the slogan element.|
 |info|.SCCategoryHeader-info|Styles applied to the info element.|
 |followedCounter|.SCCategoryHeader-followed-by-counter|Styles applied to the followers counter element.|
 |followed|.SCCategoryHeader-followed|Styles applied to the followers avatars section.|
 |action|.SCCategoryHeader-action|Styles applied to the action section.|

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

  const {
    className,
    categoryId,
    category,
    FollowCategoryButtonProps = {},
    FollowedByDialogProps = {}
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


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

  const {
    scCategory,
    setSCCategory
  } = (0, _core.useSCFetchCategory)({
    id: categoryId,
    category
  });
  const [loading, setLoading] = (0, _react.useState)(true);
  const [next, setNext] = (0, _react.useState)(null);
  const [total, setTotal] = (0, _react.useState)(0);
  const [followers, setFollowers] = (0, _react.useState)([]);
  const [openFollowersDialog, setOpenFollowersDialog] = (0, _react.useState)(false); // INTL

  const intl = (0, _reactIntl.useIntl)();
  /**
   * If id attempts to get the category by id
   */

  (0, _react.useEffect)(() => {
    if (scCategory) {
      fetchFollowers();
    }
  }, [scCategory]);
  /**
   * Memoized fetchFollowers
   */

  const fetchFollowers = (0, _react.useMemo)(() => () => {
    _core.http.request({
      url: next ? next : _core.Endpoints.CategoryFollowers.url({
        id: scCategory.id
      }),
      method: _core.Endpoints.CategoryFollowers.method
    }).then(res => {
      if (res.status >= 300) {
        return Promise.reject(res);
      }

      setFollowers([...followers, ...res.data.results]);
      setTotal(res.data['count']);
      setNext(res.data['next']);
      setLoading(false);
      return Promise.resolve(res.data);
    });
  }, [scCategory, next]);
  /**
   * Opens dialog votes
   */

  function handleToggleFollowersDialog() {
    setOpenFollowersDialog(prev => !prev);
  }
  /**
   * Handles callback follow/unfollow category
   */


  function handleFollowCategory(category, follow) {
    let _followers = [];

    if (follow) {
      // if I follow him now I add at the head of the group
      _followers = [...[scUserContext.user], ...followers];
    } else {
      // if now I don't follow category anymore
      // I remove my avatar from the visible group
      if (total < 5) {
        _followers = [...followers.filter(u => u.id !== scUserContext.user.id)];
      } else {
        const _pFollowers = followers.slice(0, 5).filter(u => u.id !== scUserContext.user.id);

        _followers = [..._pFollowers, ...followers.slice(5)];
      }
    }

    setTotal(prev => prev + (follow ? 1 : -1));
    setFollowers(_followers);
    setNext(null);
  }
  /**
   * If not category object returns null
   */


  if (!scCategory) {
    return null;
  }

  const _backgroundCover = Object.assign({}, scCategory ? {
    background: `url('${scCategory.emotional_image_original}') center / cover`
  } : {});
  /**
   * Renders root object
   */


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: (0, _classnames.default)(classes.root, className)
  }, rest), /*#__PURE__*/_react.default.createElement(_material.Paper, {
    style: _backgroundCover,
    classes: {
      root: classes.cover
    }
  }), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.info
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: "h3",
    className: classes.name,
    gutterBottom: true
  }, scCategory.name), scCategory.slogan && /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: "h5",
    className: classes.slogan
  }, scCategory.slogan), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.followed
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.followedCounter,
    component: "div"
  }, intl.formatMessage(messages.followedBy, {
    total: total
  })), loading && !scCategory ? /*#__PURE__*/_react.default.createElement(_AvatarGroupSkeleton.default, rest) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, total > 0 ? /*#__PURE__*/_react.default.createElement(_material.Button, {
    onClick: handleToggleFollowersDialog,
    disabled: loading || !scCategory
  }, /*#__PURE__*/_react.default.createElement(_material.AvatarGroup, rest, followers.map(c => /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    key: c.id,
    alt: c.username,
    src: c.avatar
  })), [...Array(Math.max(0, total - followers.length))].map((x, i // Add max to 0 to prevent creation of array with negative index during state update
  ) => /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    key: i
  })))) : 'No users followed this category')), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.action
  }, /*#__PURE__*/_react.default.createElement(_FollowCategoryButton.default, _extends({
    category: scCategory,
    onFollow: handleFollowCategory
  }, FollowCategoryButtonProps)))), openFollowersDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, _extends({
    title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.categoryHeader.followers",
      id: "ui.categoryHeader.followers"
    }), " (", total, ")"),
    onClose: handleToggleFollowersDialog,
    open: openFollowersDialog
  }, FollowedByDialogProps), loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: total,
    next: fetchFollowers,
    hasMore: next !== null,
    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.categoryHeader.noOtherFollowers",
      defaultMessage: "ui.categoryHeader.noOtherFollowers"
    })))
  }, /*#__PURE__*/_react.default.createElement(_material.List, null, followers.map((follower, index) => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: follower.id
  }, /*#__PURE__*/_react.default.createElement(_User.default, {
    elevation: 0,
    user: follower,
    key: index
  })))))));
}