"use strict";

exports.__esModule = true;
exports.default = IncubatorSuggestion;

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

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

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

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

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

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

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

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

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

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

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

var _IncubatorDetail = _interopRequireDefault(require("../IncubatorDetail"));

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

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 = 'SCIncubatorSuggestion';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  incubatorItem: `${PREFIX}-incubator-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),
  '& .MuiListItem-root': {
    display: 'block',
    padding: 0
  },
  ' & .MuiCardContent-root': {
    padding: theme.spacing(1),
    '&:last-child': {
      paddingBottom: theme.spacing(1)
    }
  }
}));

/**
 > API documentation for the Community-UI Incubator Suggestion component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {IncubatorSuggestion} from '@selfcommunity/ui';
 ```

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

 #### CSS

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


 * @param inProps
 */
function IncubatorSuggestion(inProps) {
  // CONST
  const limit = 2; // PROPS

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

  const {
    autoHide = true,
    className,
    IncubatorProps = {}
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


  const scUserContext = (0, _core.useSCUser)();
  const authUserId = scUserContext.user ? scUserContext.user.id : null; // STATE

  const [incubators, setIncubators] = (0, _react.useState)([]);
  const [visibleIncubators, setVisibleIncubators] = (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 [openIncubatorsDialog, setOpenIncubatorsDialog] = (0, _react.useState)(false);
  const [openIncubatorDetailDialog, setOpenIncubatorDetailDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.GetIncubatorSuggestion.url()}?limit=10`);
  const [detailObj, setDetailObj] = (0, _react.useState)(null); // HANDLERS

  function handleIncubatorDetailDialogOpening(incubator) {
    setOpenIncubatorDetailDialog(true);
    setOpenIncubatorsDialog(false);
    setDetailObj(incubator);
  }

  const handleIncubatorDetailDialogClose = () => {
    setOpenIncubatorDetailDialog(false);
  };
  /**
   * Fetches incubator suggestion list
   */


  function fetchIncubatorSuggestion() {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.GetIncubatorSuggestion.method
      }).then(res => {
        const data = res.data;
        setIncubators([...incubators, ...data]);
        setHasMore(data.length > visibleIncubators);
        setNext(data['next']);
        setLoading(false);
        setTotal(data.length);
      }).catch(error => {
        setLoading(false);

        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * On mount, if user is authenticated, fetches suggested incubators list
   */


  (0, _react.useEffect)(() => {
    if (scUserContext.user) {
      fetchIncubatorSuggestion();
    }
  }, [authUserId]);
  /**
   * Handles subscriptions counter update on subscribe/unsubscribe action.
   * @param incubator
   */

  function handleSubscriptionsUpdate(incubator) {
    const newIncubators = [...incubators];
    const index = newIncubators.findIndex(i => i.id === incubator.id);

    if (index !== -1) {
      if (incubator.subscribed) {
        newIncubators[index].subscribers_count = incubator.subscribers_count - 1;
        newIncubators[index].subscribed = !incubator.subscribed;
      } else {
        newIncubators[index].subscribers_count = incubator.subscribers_count + 1;
        newIncubators[index].subscribed = !incubator.subscribed;
      }

      setIncubators(newIncubators);
    }
  }
  /**
   * Renders suggested incubators list
   */


  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, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.title,
    variant: 'h5'
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.IncubatorSuggestion.title",
    defaultMessage: "ui.IncubatorSuggestion.title"
  })), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.IncubatorSuggestion.noResults",
    defaultMessage: "ui.IncubatorSuggestion.noResults"
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.List, null, incubators.slice(0, visibleIncubators).map(incubator => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: incubator.id
  }, /*#__PURE__*/_react.default.createElement(_Incubator.default, _extends({
    elevation: 0,
    incubator: incubator,
    className: classes.incubatorItem,
    subscribeButtonProps: {
      onSubscribe: handleSubscriptionsUpdate
    },
    ButtonProps: {
      onClick: () => handleIncubatorDetailDialogOpening(incubator)
    }
  }, IncubatorProps))))), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    className: classes.showMore,
    size: "small",
    onClick: () => setOpenIncubatorsDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.IncubatorSuggestion.ShowAll",
    defaultMessage: "ui.IncubatorSuggestion.ShowAll"
  }))), openIncubatorsDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.IncubatorSuggestion.title",
      defaultMessage: "ui.IncubatorSuggestion.title"
    }),
    onClose: () => setOpenIncubatorsDialog(false),
    open: openIncubatorsDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: incubators.length,
    next: fetchIncubatorSuggestion,
    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.IncubatorSuggestion.noMoreIncubators",
      defaultMessage: "ui.IncubatorSuggestion.noMoreIncubators"
    })))
  }, /*#__PURE__*/_react.default.createElement(_material.List, null, incubators.map(i => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: i.id,
    sx: {
      display: 'block',
      padding: 0
    }
  }, /*#__PURE__*/_react.default.createElement(_Incubator.default, _extends({
    elevation: 0,
    incubator: i,
    className: classes.incubatorItem,
    subscribeButtonProps: {
      onSubscribe: handleSubscriptionsUpdate
    },
    ButtonProps: {
      onClick: () => handleIncubatorDetailDialogOpening(i)
    }
  }, IncubatorProps))))))), openIncubatorDetailDialog && /*#__PURE__*/_react.default.createElement(_IncubatorDetail.default, {
    open: openIncubatorDetailDialog,
    onClose: handleIncubatorDetailDialogClose,
    incubator: detailObj,
    onSubscriptionsUpdate: handleSubscriptionsUpdate
  })));
  /**
   * Renders root object (if results and autoHide prop is set to false, otherwise component is hidden)
   */


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

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

  return null;
}