"use strict";

exports.__esModule = true;
exports.default = IncubatorDetail;

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

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

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

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

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

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

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

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

var _Incubator = _interopRequireDefault(require("../Incubator"));

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

var _reactShare = require("react-share");

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

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

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

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

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

const _excluded = ["incubator", "incubatorId", "className", "open", "onClose", "IncubatorProps", "onSubscriptionsUpdate"];

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)({
  intro: {
    id: 'ui.incubatorDetail.intro',
    defaultMessage: 'ui.incubatorDetail.intro'
  }
});
const PREFIX = 'SCIncubatorDetail';
const classes = {
  root: `${PREFIX}-root`,
  avatar: `${PREFIX}-avatar`,
  title: `${PREFIX}-title`,
  author: `${PREFIX}-author`,
  shareCard: `${PREFIX}-share-card`,
  copyUrlForm: `${PREFIX}-copy-url-form`,
  copyButton: `${PREFIX}-copy-button`,
  copyText: `${PREFIX}-copy-text`,
  shareSection: `${PREFIX}-share-section`,
  socialShareButton: `${PREFIX}-social-share-button`,
  subscribers: `${PREFIX}-subscribers`
};
const Root = (0, _styles.styled)(_BaseDialog.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  ' & .MuiCardContent-root': {
    '&:last-child': {
      paddingBottom: 0
    }
  },
  [theme.breakpoints.down(500)]: {
    minWidth: 300
  },
  [`& .${classes.avatar}`]: {
    marginRight: theme.spacing(1),
    marginBottom: theme.spacing(3)
  },
  [`& .${classes.title}`]: {
    fontSize: '1rem',
    whiteSpace: 'pre-line'
  },
  [`& .${classes.copyUrlForm}`]: {
    flexDirection: 'row',
    marginBottom: theme.spacing(1)
  },
  [`& .${classes.copyButton}`]: {
    borderRadius: 0
  },
  [`& .${classes.copyText}`]: {
    width: '80%',
    '& .MuiInputBase-root': {
      borderRadius: 0,
      '& .MuiOutlinedInput-input': {
        padding: theme.spacing(1)
      }
    }
  },
  [`& .${classes.shareSection}`]: {
    marginTop: theme.spacing(1)
  },
  [`& .${classes.socialShareButton}`]: {
    marginRight: theme.spacing(1)
  },
  [`& .${classes.subscribers}`]: {
    marginTop: theme.spacing(1),
    '& .MuiAvatar-root': {
      color: theme.palette.common.white,
      border: '2px solid #FFF'
    }
  }
}));

/**
 * > API documentation for the Community-UI Incubator Detail component. Learn about the available props and the CSS API.
 *
 * #### Import
 ```jsx
 import {IncubatorDetail} from '@selfcommunity/ui';
 ```
 #### Component Name
 The name `SCIncubatorDetail` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCIncubatorDetail-root|Styles applied to the root element.|
 |avatar|.SCIncubatorDetail-avatar|Styles applied to the avatar element.|
 |title|.SCIncubatorDetail-title|Styles applied to the title element.|
 |author|.SCIncubatorDetail-author|Styles applied to the author element.|
 |shareCard|.SCIncubatorDetail-share-card|Styles applied to the  section card.|
 |copyUrlForm|.SCIncubatorDetail-copy-url-form|Styles applied to the url copy section.|
 |copyButton|.SCIncubatorDetail-copy-button|Styles applied to the copy button element.|
 |copyText|.SCIncubatorDetail-copy-text|Styles applied to the text copy element.|
 |shareSection|.SCIncubatorDetail-share-section|Styles applied to the social share section.|
 |socialShareButton|.SCIncubatorDetail-social-share-button|Styles applied to the social share button.|
 |subscribers|.SCIncubatorDetail-subscribers|Styles applied to the subscribers avatar section.|
* @param inProps
*/
function IncubatorDetail(inProps) {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    incubator,
    className,
    open,
    onClose,
    IncubatorProps = {},
    onSubscriptionsUpdate
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const [alert, setAlert] = (0, _react.useState)(false);
  const {
    scIncubator,
    setSCIncubator
  } = (0, _core.useSCFetchIncubator)({
    id: incubator.id,
    incubator
  });
  const [loading, setLoading] = (0, _react.useState)(true);
  const [next, setNext] = (0, _react.useState)(incubator.id || scIncubator ? `${_core.Endpoints.GetIncubatorSubscribers.url({
    id: incubator ? incubator.id : scIncubator.id
  })}?limit=10` : null);
  const [total, setTotal] = (0, _react.useState)(0);
  const [subscribers, setSubscribers] = (0, _react.useState)([]);
  const [openSubscribersDialog, setOpenSubscribersDialog] = (0, _react.useState)(false); // CONTEXT

  const scUserContext = (0, _core.useSCUser)();
  const scContext = (0, _core.useSCContext)();
  const scRoutingContext = (0, _core.useSCRouting)();
  const portal = scContext.settings.portal + scRoutingContext.url(_core.SCRoutes.INCUBATOR_ROUTE_NAME, scIncubator); // INTL

  const intl = (0, _reactIntl.useIntl)(); // HANDLERS

  /**
   * Copies incubator path on clipboard and notifies user
   */

  const copy = async () => {
    await navigator.clipboard.writeText(portal);
    setAlert(true);
  };
  /**
   * Opens subscribers dialog
   */


  function handleToggleSubscribersDialog() {
    setOpenSubscribersDialog(prev => !prev);
  }
  /**
   * Handles incubator subscribe/unsubscribe callback
   */


  function handleSubscribersUpdate(incubator, subscribed) {
    let _subscribers = [];

    if (subscribed) {
      _subscribers = [...[scUserContext.user], ...subscribers];
    } else {
      if (total < 5) {
        _subscribers = [...subscribers.filter(u => u.id !== scUserContext.user.id)];
      } else {
        const _pSubscribers = subscribers.slice(0, 5).filter(u => u.id !== scUserContext.user.id);

        _subscribers = [..._pSubscribers, ...subscribers.slice(5)];
      }
    }

    setTotal(prev => prev + (subscribed ? 1 : -1));
    setSubscribers(_subscribers);
    setNext(null);
  }
  /**
   * Handles subscription counter and subscribers update callbacks on subscribe/unsubscribe action
   */


  const handleUpdates = (incubator, subscribed) => {
    onSubscriptionsUpdate(incubator);
    handleSubscribersUpdate(incubator, subscribed);
  };
  /**
   * If id attempts to get the incubator by id
   */


  (0, _react.useEffect)(() => {
    if (scIncubator) {
      fetchSubscribers();
    }
  }, [scIncubator]);
  /**
   * Fetches incubator subscribers
   */

  const fetchSubscribers = (0, _react.useMemo)(() => () => {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.GetIncubatorSubscribers.method
      }).then(res => {
        if (res.status < 300) {
          setSubscribers([...subscribers, ...res.data.results]);
          setTotal(res.data['count']);
          setNext(res.data['next']);
          setLoading(false);
        }
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }, [scIncubator, next, loading]);
  /**
   * If not incubator object returns null
   */

  if (!scIncubator) {
    return null;
  }
  /**
   * Renders root element
   */


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Avatar, {
      className: classes.avatar,
      alt: scIncubator.user.avatar,
      src: scIncubator.user.avatar
    }), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
      className: classes.title
    }, `${intl.formatMessage(messages.intro, {
      name: scIncubator.name
    })}`, " "), /*#__PURE__*/_react.default.createElement(_material.Typography, {
      component: 'span'
    }, /*#__PURE__*/_react.default.createElement(_core.Link, {
      to: scRoutingContext.url(_core.SCRoutes.USER_PROFILE_ROUTE_NAME, scIncubator.user)
    }, "@", scIncubator.user.username)))),
    open: open,
    onClose: onClose,
    className: (0, _classnames.default)(classes.root, className)
  }, rest), /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement(_Incubator.default, _extends({
    elevation: 0,
    incubator: scIncubator,
    detailView: true,
    subscribeButtonProps: {
      onSubscribe: handleUpdates
    }
  }, IncubatorProps)), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.subscribers
  }, loading && !scIncubator ? /*#__PURE__*/_react.default.createElement(_AvatarGroupSkeleton.default, rest) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, total > 0 ? /*#__PURE__*/_react.default.createElement(_material.Button, {
    onClick: handleToggleSubscribersDialog,
    disabled: loading || !scIncubator
  }, /*#__PURE__*/_react.default.createElement(_material.AvatarGroup, rest, subscribers.map(u => /*#__PURE__*/_react.default.createElement(_material.Avatar, {
    key: u.id,
    alt: u.username,
    src: u.avatar
  })), [...Array(Math.max(0, total - subscribers.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
  })))) : null)), openSubscribersDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.incubatorDetail.subscribersSection.title",
      id: "ui.incubatorDetail.subscribersSection.title"
    }), " (", total, ")"),
    onClose: handleToggleSubscribersDialog,
    open: openSubscribersDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: total,
    next: fetchSubscribers,
    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.incubatorDetail.subscribersSection.noMoreSubscribers",
      defaultMessage: "ui.incubatorDetail.subscribersSection.noMoreSubscribers"
    })))
  }, /*#__PURE__*/_react.default.createElement(_material.List, null, subscribers.map((s, index) => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: (s.id, index)
  }, /*#__PURE__*/_react.default.createElement(_User.default, {
    elevation: 0,
    user: s,
    key: index
  })))))), /*#__PURE__*/_react.default.createElement(_Widget.default, {
    elevation: 1,
    className: classes.shareCard
  }, /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'h6'
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorDetail.shareSection.title",
    defaultMessage: "ui.incubatorDetail.shareSection.title"
  })), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'subtitle1'
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorDetail.shareSection.share",
    defaultMessage: "ui.incubatorDetail.shareSection.share"
  })), /*#__PURE__*/_react.default.createElement(_material.FormGroup, {
    className: classes.copyUrlForm
  }, /*#__PURE__*/_react.default.createElement(_material.TextField, {
    className: classes.copyText,
    variant: "outlined",
    value: portal
  }), /*#__PURE__*/_react.default.createElement(_material.Button, {
    className: classes.copyButton,
    variant: "contained",
    onClick: copy
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorDetail.shareSection.button.copy",
    defaultMessage: "ui.incubatorDetail.shareSection.button.copy"
  }))), alert && /*#__PURE__*/_react.default.createElement(_material.Alert, {
    onClose: () => setAlert(false)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorDetail.shareSection.copied",
    defaultMessage: "ui.incubatorDetail.shareSection.copied"
  })), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: 'subtitle2'
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.incubatorDetail.shareSection.invite",
    defaultMessage: "ui.incubatorDetail.shareSection.invite"
  })), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.shareSection
  }, /*#__PURE__*/_react.default.createElement(_reactShare.LinkedinShareButton, {
    url: portal,
    className: classes.socialShareButton
  }, /*#__PURE__*/_react.default.createElement(_reactShare.LinkedinIcon, {
    size: 32,
    round: true
  })), /*#__PURE__*/_react.default.createElement(_reactShare.TwitterShareButton, {
    url: portal
  }, /*#__PURE__*/_react.default.createElement(_reactShare.TwitterIcon, {
    size: 32,
    round: true
  })))))));
}