"use strict";

exports.__esModule = true;
exports.default = RelatedFeedObjects;

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

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

var _List = _interopRequireDefault(require("@mui/material/List"));

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

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

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

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

var _FeedObject = _interopRequireDefault(require("../FeedObject"));

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

var _feedObject = require("../../types/feedObject");

var _CustomAdv = _interopRequireDefault(require("../CustomAdv"));

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

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

const _excluded = ["feedObjectId", "feedObjectType", "template", "FeedObjectProps", "className", "autoHide"];

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 = 'SCRelatedFeedObjects';
const classes = {
  root: `${PREFIX}-root`,
  title: `${PREFIX}-title`,
  noResults: `${PREFIX}-no-results`,
  relatedItem: `${PREFIX}-related-item`,
  showMore: `${PREFIX}-show-more`
};
const Root = (0, _styles.styled)(_Widget.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  maxWidth: 500,
  marginBottom: theme.spacing(2),
  [`& .${classes.relatedItem}`]: {
    marginBottom: 0
  }
}));
const PREFERENCES = [_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED, _core.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED];
/**
 *> API documentation for the Community-UI Related FeedObjects component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {RelatedFeedObjects} from '@selfcommunity/ui';
 ```

 #### Component Name

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCRelatedFeedObjects-root|Styles applied to the root element.|
 |title|.SCRelatedFeedObjects-title|Styles applied to the title element.|
 |no-results|.SCRelatedFeedObjects-no-results|Styles applied to no results section.|
 |relatedItem|.SCRelatedFeedObjects-related-item|Styles applied to the related item element.|
 |showMore|.SCRelatedFeedObjects-show-more|Styles applied to show more button element.|

 *
 * @param inProps
 */

function RelatedFeedObjects(inProps) {
  // CONST
  const limit = 4; // CONTEXT

  const scPreferences = (0, _core.useSCPreferences)();
  const scUserContext = (0, _core.useSCUser)(); // PROPS

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

  const {
    feedObjectId,
    feedObjectType,
    template = _feedObject.SCFeedObjectTemplateType.SNIPPET,
    FeedObjectProps = {},
    className,
    autoHide = true
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // STATE


  const {
    obj,
    setObj
  } = (0, _core.useSCFetchFeedObject)({
    id: feedObjectId,
    feedObject: null,
    feedObjectType
  });
  const [objs, setObjs] = (0, _react.useState)([]);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [hasMore, setHasMore] = (0, _react.useState)(false);
  const [total, setTotal] = (0, _react.useState)(0);
  const [visibleDiscussions, setVisibleDiscussions] = (0, _react.useState)(limit);
  const [openRelatedFeedObjectsDialog, setOpenRelatedFeedObjectsDialog] = (0, _react.useState)(false);
  const [next, setNext] = (0, _react.useState)(`${_core.Endpoints.RelatedFeedObjects.url({
    type: feedObjectType,
    id: feedObjectId
  })}?limit=10`);
  /**
   * Compute preferences
   */

  const preferences = (0, _react.useMemo)(() => {
    const _preferences = {};
    PREFERENCES.map(p => _preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null);
    return _preferences;
  }, [scPreferences.preferences]);
  /**
   * Render advertising
   */

  function renderAdvertising() {
    if (preferences[_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED] && (preferences[_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED] && scUserContext.user === null || !preferences[_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED])) {
      return /*#__PURE__*/_react.default.createElement(_CustomAdv.default, _extends({
        position: _core.SCCustomAdvPosition.POSITION_RELATED_POSTS_COLUMN
      }, obj.categories.length && {
        categoriesId: obj.categories.map(c => c.id)
      }));
    }

    return null;
  }
  /**
   * Fetches related discussions list
   */


  function fetchRelated() {
    if (next) {
      _core.http.request({
        url: next,
        method: _core.Endpoints.RelatedFeedObjects.method
      }).then(res => {
        const data = res.data;
        setObjs([...objs, ...data.results]);
        setHasMore(data.count > visibleDiscussions);
        setLoading(false);
        setTotal(data.count);
        setNext(data['next']);
      }).catch(error => {
        _core.Logger.error(_Errors.SCOPE_SC_UI, error);
      });
    }
  }
  /**
   * On mount, fetches related discussions list
   */


  (0, _react.useEffect)(() => {
    fetchRelated();
  }, []);
  /**
   * Renders related discussions list
   */

  const advPosition = Math.floor(Math.random() * (Math.min(total, 5) - 1 + 1) + 1);

  const d = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, loading ? /*#__PURE__*/_react.default.createElement(_Skeleton.default, {
    elevation: 0
  }) : /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.title,
    variant: "h5"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.relatedFeedObjects.title",
    defaultMessage: "ui.relatedFeedObjects.title"
  })), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    className: classes.noResults,
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.relatedFeedObjects.noResults",
    defaultMessage: "ui.relatedFeedObjects.noResults"
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_List.default, null, objs.slice(0, visibleDiscussions).map((obj, index) => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
      key: obj.id
    }, /*#__PURE__*/_react.default.createElement(_material.ListItem, null, /*#__PURE__*/_react.default.createElement(_FeedObject.default, _extends({
      elevation: 0,
      feedObject: obj,
      template: template,
      className: classes.relatedItem
    }, FeedObjectProps))), advPosition === index && /*#__PURE__*/_react.default.createElement(_material.ListItem, null, renderAdvertising()));
  })), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    className: classes.showMore,
    onClick: () => setOpenRelatedFeedObjectsDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.relatedFeedObjects.button.showMore",
    defaultMessage: "ui.relatedFeedObjects.button.showMore"
  }))), openRelatedFeedObjectsDialog && /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.relatedFeedObjects.title",
      defaultMessage: "ui.relatedFeedObjects.title"
    }),
    onClose: () => setOpenRelatedFeedObjectsDialog(false),
    open: openRelatedFeedObjectsDialog
  }, loading ? /*#__PURE__*/_react.default.createElement(_CentralProgress.default, {
    size: 50
  }) : /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    dataLength: objs.length,
    next: fetchRelated,
    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.relatedFeedObjects.noMoreResults",
      defaultMessage: "ui.relatedFeedObjects.noMoreResults"
    })))
  }, /*#__PURE__*/_react.default.createElement(_List.default, null, objs.map(obj => /*#__PURE__*/_react.default.createElement(_material.ListItem, {
    key: obj.id
  }, /*#__PURE__*/_react.default.createElement(_FeedObject.default, _extends({
    elevation: 0,
    feedObject: obj,
    template: template,
    className: classes.relatedItem
  }, FeedObjectProps)))))))));
  /**
   * 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), d);
}