"use strict";

exports.__esModule = true;
exports.default = ContributorsFeedObject;

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

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

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

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

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

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

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 _User = _interopRequireDefault(require("../../User"));

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

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

const _excluded = ["className", "feedObjectId", "feedObject", "feedObjectType"];

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 = 'SCContributorsFeedObject';
const classes = {
  root: `${PREFIX}-root`,
  avatarGroup: `${PREFIX}-avatarGroup`,
  avatar: `${PREFIX}-avatar`,
  btnParticipants: `${PREFIX}-btn-participants`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  marginTop: 0,
  marginBottom: 0,
  [`& .${classes.btnParticipants}`]: {
    marginLeft: -10
  },
  ['& .MuiAvatarGroup-root']: {
    justifyContent: 'flex-end'
  },
  ['& .MuiAvatar-root']: {
    backgroundColor: '#d5d5d5',
    border: '2px solid #FFF !important',
    color: '#FFF',
    fontSize: '0.55rem',
    width: 24,
    height: 24,
    marginLeft: -7,
    lineHeight: '24px'
  }
}));

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

  const {
    className = null,
    feedObjectId = null,
    feedObject = null,
    feedObjectType = null
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const {
    obj,
    setObj
  } = (0, _core.useSCFetchFeedObject)({
    id: feedObjectId,
    feedObject,
    feedObjectType
  });
  const [loading, setLoading] = (0, _react.useState)(true);
  const [total, setTotal] = (0, _react.useState)(0);
  const [contributors, setContributors] = (0, _react.useState)([]);
  const [openContributorsDialog, setOpenContributorsDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(feedObjectId || obj ? `${_core.Endpoints.Contributors.url({
    id: feedObjectId ? feedObjectId : obj['id'],
    type: feedObjectType
  })}?limit=10` : null);
  /**
   * Fetches contributors
   */

  const fetchContributors = (0, _react.useMemo)(() => () => {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.Contributors.method
      }).then(res => {
        if (res.status < 300) {
          const data = res.data;
          setContributors([...contributors, ...data['results']]);
          setTotal(data['count']);
          setNext(data['next']);
          setLoading(false);
        }
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }, [obj, contributors, next, loading]);
  /**
   * On mount fetches contributors
   */

  (0, _react.useEffect)(() => {
    if (obj) {
      fetchContributors();
    }
  }, [obj]);
  /**
   * Renders root object (if obj)
   */

  if (!obj) {
    return null;
  }

  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: (0, _classnames.default)(classes.root, className)
  }, rest), loading && !openContributorsDialog ? /*#__PURE__*/_react.default.createElement(_material.Button, {
    variant: "text",
    disabled: true,
    classes: {
      root: classes.btnParticipants
    }
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: 'ui.feedObject.contributors.participants',
    defaultMessage: 'ui.feedObject.contributors.participants'
  }), ":", /*#__PURE__*/_react.default.createElement(_AvatarGroupSkeleton.default, rest)) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, contributors.length > 0 ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Button, {
    variant: "text",
    onClick: () => setOpenContributorsDialog(true),
    classes: {
      root: classes.btnParticipants
    },
    color: "inherit"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: 'ui.feedObject.contributors.participants',
    defaultMessage: 'ui.feedObject.contributors.participants'
  }), ":", /*#__PURE__*/_react.default.createElement(_material.AvatarGroup, rest, contributors.map(c => /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    alt: c.username,
    src: c.avatar,
    key: c.id
  })), [...Array(total - contributors.length)].map((x, i) => /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    key: i
  })))), openContributorsDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.feedObject.contributors.title",
      id: "ui.feedObject.contributors.title",
      values: {
        total
      }
    }),
    onClose: () => setOpenContributorsDialog(false),
    open: openContributorsDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: contributors.length,
    next: fetchContributors,
    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.feedObject.contributors.noOtherContributors",
      defaultMessage: "ui.feedObject.contributors.noOtherContributors"
    })))
  }, /*#__PURE__*/_react.default.createElement(_material.List, null, contributors.map((c, index) => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: c.id
  }, /*#__PURE__*/_react.default.createElement(_User.default, {
    elevation: 0,
    user: c,
    key: c.id,
    sx: {
      m: 0
    }
  }))))))) : null));
}