"use strict";

exports.__esModule = true;
exports.default = IncubatorsList;

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 _Popover = _interopRequireDefault(require("@mui/material/Popover"));

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

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

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

var _CreateIncubatorDialog = _interopRequireDefault(require("./CreateIncubatorDialog"));

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 = 'SCIncubatorsList';
const classes = {
  root: `${PREFIX}-root`,
  header: `${PREFIX}-header`,
  title: `${PREFIX}-title`,
  incubatorItem: `${PREFIX}-incubator-item`,
  noResults: `${PREFIX}-no-results`,
  actions: `${PREFIX}-actions`,
  helpPopover: `${PREFIX}-help-popover`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  marginBottom: theme.spacing(2),
  [`& .${classes.header}`]: {
    display: 'flex',
    alignItems: 'center'
  },
  [`& .${classes.actions}`]: {
    display: 'flex',
    justifyContent: 'space-between'
  },
  '& .MuiListItem-root': {
    display: 'block',
    padding: 0
  },
  '& .MuiCardContent-root': {
    padding: theme.spacing(1),
    '&:last-child': {
      paddingBottom: theme.spacing(1)
    }
  }
}));

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

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCIncubatorsList-root|Styles applied to the root element.|
 |header|.SCIncubatorsList-header|Styles applied to the header element.|
 |title|.SCIncubatorsList-title|Styles applied to the title element.|
 |incubatorItem|.SCIncubatorsList-incubator-item|Styles applied to the incubator item element.|
 |noResults|.SCIncubatorsList-no-results|Styles applied to the no results section.|
 |actions|.SCIncubatorsList-actions|Styles applied to the actions section.|
 |helpPopover|.SCIncubatorsList-help-popover|Styles applied to the help popover element.|

 * @param inProps
 */
function IncubatorsList(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); // 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 [openCreateIncubatorDialog, setOpenCreateIncubatorDialog] = (0, _react.useState)(false);
  const [openIncubatorDetailDialog, setOpenIncubatorDetailDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.GetAllIncubators.url()}?limit=10`);

  const [anchorEl, setAnchorEl] = _react.default.useState(null);

  const isOpen = Boolean(anchorEl);
  const [detailObj, setDetailObj] = (0, _react.useState)(null); // HANDLERS

  const handleClickHelpButton = event => {
    setAnchorEl(event.currentTarget);
  };

  const handlePopoverClose = () => {
    setAnchorEl(null);
  };

  const handleCreateIncubatorDialogClose = () => {
    setOpenCreateIncubatorDialog(false);
  };

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

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


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

        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * On mount, fetches  incubators list
   */


  (0, _react.useEffect)(() => {
    fetchIncubators();
  }, []);
  /**
   * 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 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.Box, {
    className: classes.header
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.title,
    variant: 'h5'
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorsList.title",
    defaultMessage: "ui.incubatorsList.title"
  })), /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    className: classes.helpPopover,
    color: "primary",
    "aria-label": "info",
    component: "span",
    onClick: handleClickHelpButton
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "help_outline")), isOpen && /*#__PURE__*/_react.default.createElement(_Popover.default, {
    open: isOpen,
    anchorEl: anchorEl,
    onClose: handlePopoverClose,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'right'
    }
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    sx: {
      p: '10px'
    }
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    component: 'span',
    sx: {
      whiteSpace: 'pre-line'
    }
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorsList.popover",
    defaultMessage: "ui.incubatorsList.popover"
  }))))), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorsList.noResults",
    defaultMessage: "ui.incubatorsList.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))))), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.actions
  }, hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    onClick: () => setOpenIncubatorsDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorsList.ShowAll",
    defaultMessage: "ui.incubatorsList.ShowAll"
  })), /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    onClick: () => setOpenCreateIncubatorDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorsList.SuggestNewTopic",
    defaultMessage: "ui.incubatorsList.SuggestNewTopic"
  })))), openIncubatorsDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.incubatorsList.title",
      defaultMessage: "ui.incubatorsList.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: fetchIncubators,
    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.incubatorsList.noMoreIncubators",
      defaultMessage: "ui.incubatorsList.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))))))), openCreateIncubatorDialog && /*#__PURE__*/_react.default.createElement(_CreateIncubatorDialog.default, {
    open: openCreateIncubatorDialog,
    onClose: handleCreateIncubatorDialogClose
  }), 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;
  }

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