"use strict";

exports.__esModule = true;
exports.default = void 0;

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

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

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

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

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

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

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

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

var _reactStickynode = _interopRequireDefault(require("react-stickynode"));

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

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

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

var _pubsubJs = _interopRequireDefault(require("pubsub-js"));

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

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

const PREFIX = 'SCFeed';
const classes = {
  root: `${PREFIX}-root`,
  left: `${PREFIX}-left`,
  right: `${PREFIX}-right`,
  end: `${PREFIX}-end`,
  refresh: `${PREFIX}-refresh`
};
const Root = (0, _styles.styled)(_material.Grid, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  marginTop: theme.spacing(-2),
  [`& .${classes.left}`]: {
    padding: '0 2px 0 2px',
    [theme.breakpoints.down('md')]: {
      '& > .SCWidget-root, & > .SCCustomAdv-root': {
        maxWidth: 700,
        marginLeft: 'auto',
        marginRight: 'auto'
      }
    }
  },
  [`& .${classes.end}, & .${classes.refresh}`]: {
    textAlign: 'center'
  }
}));
const PREFERENCES = [_core.SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED, _core.SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED];
/**
 * > API documentation for the Community-UI Feed component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCFeed-root|Styles applied to the root element.|
 |left|.SCFeed-left|Styles applied to the left element.|
 |right|.SCFeed-right|Styles applied to the right element.|
 |end|.SCFeed-end|Styles applied to the end element.|
 |refresh|.SCFeed-refresh|Styles applied to the refresh section.|
 *
 * @param inProps
 */

const Feed = (inProps, ref) => {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });
  const {
    id = 'feed',
    className,
    endpoint,
    endMessage = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.feed.noOtherFeedObject",
      defaultMessage: "ui.feed.noOtherFeedObject"
    }),
    refreshMessage = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.feed.refreshRelease",
      defaultMessage: "ui.feed.refreshRelease"
    }),
    widgets = [],
    ItemComponent,
    itemPropsGenerator,
    itemIdGenerator,
    ItemProps = {},
    ItemSkeleton,
    ItemSkeletonProps = {},
    onFetchData,
    FeedSidebarProps = {
      top: 0,
      bottomBoundary: `#${id}`
    },
    CustomAdvProps = {}
  } = props; // STATE

  const [feedData, setFeedData] = (0, _react.useState)([]);
  const [loading, setLoading] = (0, _react.useState)(true);
  const [next, setNext] = (0, _react.useState)(endpoint.url({})); // CONTEXT

  const scPreferences = (0, _core.useSCPreferences)();
  const scUserContext = (0, _react.useContext)(_core.SCUserContext); // CONST

  const authUserId = scUserContext.user ? scUserContext.user.id : null; // REFS

  const refreshSubscription = (0, _react.useRef)(null);
  /**
   * 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]);
  /**
   * Compute Widgets
   */

  const _widgets = (0, _react.useMemo)(() => {
    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 [...widgets, {
        type: 'widget',
        component: _CustomAdv.default,
        componentProps: Object.assign({
          position: _core.SCCustomAdvPosition.POSITION_FEED_SIDEBAR
        }, CustomAdvProps),
        column: 'right',
        position: 0
      }, ...Array.from({
        length: feedData.length / 10
      }, (_, i) => i * 10).map(position => {
        return {
          type: 'widget',
          component: _CustomAdv.default,
          componentProps: Object.assign({
            position: _core.SCCustomAdvPosition.POSITION_FEED
          }, CustomAdvProps),
          column: 'left',
          position
        };
      })];
    }

    return [...widgets];
  }, [widgets, feedData, preferences]);
  /**
   * Fetch main feed
   * Manage pagination, infinite scrolling
   */


  const fetch = () => {
    setLoading(true);

    _core.http.request({
      url: next,
      method: endpoint.method
    }).then(res => {
      const data = res.data;
      setFeedData([...feedData, ...data.results]);
      setNext(data.next);
      setLoading(false);
      onFetchData && onFetchData(res.data);
    }).catch(error => {
      _core.Logger.error(_Errors.SCOPE_SC_UI, error);
    });
  };

  const refresh = () => {
    setNext(endpoint.url({}));
    setFeedData([]);
    fetch();
  };

  const subscriber = (msg, data) => {
    if (data.refresh) {
      refresh();
    }
  }; // EFFECTS


  (0, _react.useEffect)(() => {
    fetch();
  }, [authUserId]);
  (0, _react.useEffect)(() => {
    refreshSubscription.current = _pubsubJs.default.subscribe(id, subscriber);
    return () => {
      _pubsubJs.default.unsubscribe(refreshSubscription.current);
    };
  }, []); // EXPOSED METHODS

  (0, _react.useImperativeHandle)(ref, () => ({
    addFeedData: data => {
      setFeedData([data, ...feedData]);
    }
  })); // RENDER

  const theme = (0, _styles.useTheme)();
  const oneColLayout = (0, _material.useMediaQuery)(theme.breakpoints.down('md'));
  const getData = (0, _react.useCallback)(() => {
    const widgetSort = (w1, w2) => w1.position > w2.position ? 1 : -1;

    const widgetReducer = (value, w) => {
      value.splice(w.position, 0, w);
      return value;
    };

    if (oneColLayout) {
      return {
        left: _widgets.map(w => Object.assign({}, w, {
          position: w.position * (w.column === 'right' ? 5 : 1)
        })).sort(widgetSort).reduce(widgetReducer, [...feedData, ...(loading ? Array.from({
          length: 5
        }).map(() => ({
          type: 'widget',
          component: ItemSkeleton,
          componentProps: ItemSkeletonProps
        })) : [])]),
        right: []
      };
    } else {
      return {
        left: _widgets.filter(w => w.column === 'left').sort(widgetSort).reduce(widgetReducer, [...feedData, ...(loading ? Array.from({
          length: 5
        }).map(() => ({
          type: 'widget',
          component: ItemSkeleton,
          componentProps: ItemSkeletonProps
        })) : [])]),
        right: _widgets.filter(w => w.column === 'right').sort(widgetSort)
      };
    }
  }, [loading, oneColLayout, feedData, _widgets]);
  const data = getData();
  return /*#__PURE__*/_react.default.createElement(Root, {
    container: true,
    spacing: 2,
    id: id,
    className: (0, _classnames.default)(classes.root, className)
  }, /*#__PURE__*/_react.default.createElement(_material.Grid, {
    item: true,
    xs: 12,
    md: 7
  }, /*#__PURE__*/_react.default.createElement(_react.default.Suspense, {
    fallback: /*#__PURE__*/_react.default.createElement(ItemSkeleton, ItemSkeletonProps)
  }, /*#__PURE__*/_react.default.createElement(_reactInfiniteScrollComponent.default, {
    className: classes.left,
    dataLength: data.left.length,
    next: fetch,
    hasMore: Boolean(next),
    loader: false,
    endMessage: /*#__PURE__*/_react.default.createElement(_Widget.default, {
      className: classes.end
    }, /*#__PURE__*/_react.default.createElement(_material.CardContent, null, endMessage)),
    refreshFunction: refresh,
    pullDownToRefresh: true,
    pullDownToRefreshThreshold: 1000,
    pullDownToRefreshContent: null,
    releaseToRefreshContent: /*#__PURE__*/_react.default.createElement(_Widget.default, {
      variant: "outlined",
      className: classes.refresh
    }, /*#__PURE__*/_react.default.createElement(_material.CardContent, null, refreshMessage)),
    style: {
      overflow: 'visible'
    }
  }, data.left.map((d, i) => d.type === 'widget' ? /*#__PURE__*/_react.default.createElement(d.component, _extends({
    key: `widget_left_${i}`
  }, d.componentProps, d.publishEvents && {
    publicationChannel: id
  })) : /*#__PURE__*/_react.default.createElement(ItemComponent, _extends({
    key: `item_${itemIdGenerator(d)}`
  }, itemPropsGenerator(scUserContext.user, d), ItemProps, {
    sx: {
      width: '100%'
    }
  })))))), data.right.length > 0 && /*#__PURE__*/_react.default.createElement(_material.Hidden, {
    smDown: true
  }, /*#__PURE__*/_react.default.createElement(_material.Grid, {
    item: true,
    xs: 12,
    md: 5
  }, /*#__PURE__*/_react.default.createElement(_reactStickynode.default, _extends({
    enabled: true,
    className: classes.right
  }, FeedSidebarProps), /*#__PURE__*/_react.default.createElement(_react.default.Suspense, {
    fallback: /*#__PURE__*/_react.default.createElement(_Skeleton.GenericSkeleton, null)
  }, data.right.map((d, i) => /*#__PURE__*/_react.default.createElement(d.component, _extends({
    key: i
  }, d.componentProps))))))));
};

var _default = /*#__PURE__*/(0, _react.forwardRef)(Feed);

exports.default = _default;