"use strict";

exports.__esModule = true;
exports.default = RelatedDiscussion;

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

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

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

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

var _Card = _interopRequireDefault(require("@mui/material/Card"));

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

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"));

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 = 'SCTrendingPost';
const Root = (0, _styles.styled)(_Card.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  maxWidth: 500,
  marginBottom: theme.spacing(2)
}));
const PREFERENCES = [_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED, _core.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED];

function RelatedDiscussion(props) {
  // CONST
  const limit = 4; // CONTEXT

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

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


  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 [openTrendingPostDialog, setOpenTrendingPostDialog] = (0, _react.useState)(false);
  /**
   * 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, {
        position: _core.SCCustomAdvPosition.POSITION_RELATED_POSTS_COLUMN
      });
    }

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


  function fetchRelated() {
    _core.http.request({
      url: _core.Endpoints.RelatedDiscussion.url({
        type: feedObjectType,
        id: feedObjectId
      }),
      method: _core.Endpoints.RelatedDiscussion.method
    }).then(res => {
      const data = res.data;
      setObjs(data.results);
      setHasMore(data.count > visibleDiscussions);
      setLoading(false);
      setTotal(data.count);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  }
  /**
   * Loads more discussions on "see more" button click
   */


  function loadDiscussions() {
    const newIndex = visibleDiscussions + limit;
    const newHasMore = newIndex < objs.length - 1;
    setVisibleDiscussions(newIndex);
    setHasMore(newHasMore);
  }
  /**
   * 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(_CardContent.default, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: "body1"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.relatedDiscussion.title",
    defaultMessage: "ui.relatedDiscussion.title"
  })), !total ? /*#__PURE__*/_react.default.createElement(_material.Typography, {
    variant: "body2"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.relatedDiscussion.noResults",
    defaultMessage: "ui.relatedDiscussion.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: index
    }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_FeedObject.default, {
      elevation: 0,
      feedObject: obj,
      key: obj.id,
      template: template
    })), advPosition === index && renderAdvertising());
  })), hasMore && /*#__PURE__*/_react.default.createElement(_material.Button, {
    size: "small",
    onClick: () => loadDiscussions()
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.button.showMore",
    defaultMessage: "ui.button.showMore"
  }))), openTrendingPostDialog && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null)));
  /**
   * Renders root object (if not hidden by autoHide prop)
   */


  if (!autoHide) {
    return /*#__PURE__*/_react.default.createElement(Root, _extends({
      className: className
    }, rest), d);
  }

  return null;
}