define(['exports', 'react', 'prop-types', 'react-helmet', 'react-intl', 'react-redux', 'react-infinite-scroller', 'redux', 'reselect', 'react-bootstrap/ListGroup', 'react-router-dom', 'react-icons/fa', 'react-bootstrap/Row', 'react-bootstrap/Col', 'styled-components', 'react-bootstrap/Container', './index-3130a914', './index-ba8ec889', './request-ddfa17c1', 'immer', './saga-5fb20c1e', 'redux-saga/effects', './TopicsListComponent-d0f74d18', 'react-bootstrap/Breadcrumb', 'hoist-non-react-statics', 'invariant', 'lodash', 'sanitize.css/sanitize.css', 'connected-react-router', 'redux-saga', 'history'], function (exports, React, PropTypes, reactHelmet, reactIntl, reactRedux, InfiniteScroll, redux, reselect, ListGroup, reactRouterDom, fa, Row, Col, styled, Container, index$2, index$1, request, produce, saga, effects, TopicsListComponent, ReactBreadcrumb, hoistNonReactStatics, invariant, lodash, sanitize_css, connectedReactRouter, createSagaMiddleware, history) { 'use strict';

  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
  var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
  var InfiniteScroll__default = /*#__PURE__*/_interopDefaultLegacy(InfiniteScroll);
  var ListGroup__default = /*#__PURE__*/_interopDefaultLegacy(ListGroup);
  var Row__default = /*#__PURE__*/_interopDefaultLegacy(Row);
  var Col__default = /*#__PURE__*/_interopDefaultLegacy(Col);
  var styled__default = /*#__PURE__*/_interopDefaultLegacy(styled);
  var Container__default = /*#__PURE__*/_interopDefaultLegacy(Container);
  var produce__default = /*#__PURE__*/_interopDefaultLegacy(produce);

  const CounterText = styled__default['default'].div.withConfig({
    displayName: "ThreadListItem__CounterText",
    componentId: "sc-1dq38fj-0"
  })(["font-size:0.7rem;"]);

  function ThreadListItem(props) {
    return /*#__PURE__*/React__default['default'].createElement(ListGroup__default['default'].Item, {
      action: true,
      onClick: props.onClick
    }, /*#__PURE__*/React__default['default'].createElement(Container__default['default'], null, /*#__PURE__*/React__default['default'].createElement(Row__default['default'], null, /*#__PURE__*/React__default['default'].createElement(Col__default['default'], {
      md: 1
    }, /*#__PURE__*/React__default['default'].createElement(fa.FaComments, {
      size: 32
    })), /*#__PURE__*/React__default['default'].createElement(Col__default['default'], {
      md: 10
    }, /*#__PURE__*/React__default['default'].createElement("h4", null, props.item.title), props.item.description), /*#__PURE__*/React__default['default'].createElement(Col__default['default'], {
      md: 1
    }, /*#__PURE__*/React__default['default'].createElement(CounterText, null, props.item.posts_counter), /*#__PURE__*/React__default['default'].createElement(CounterText, null, "Comments")))));
  }

  ThreadListItem.propTypes = {
    item: PropTypes__default['default'].any,
    onClick: PropTypes__default['default'].func
  };

  /*
   * AppConstants
   * Each action has a corresponding type, which the reducer knows and picks up on.
   * To avoid weird typos between the reducer and the actions, we save them as
   * constants here. We prefix them with 'yourproject/YourComponent' so we avoid
   * reducers accidentally picking up actions they shouldn't.
   *
   * Follow this format:
   * export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT';
   */
  const LOAD_THREADS = 'reactCommentsDjango/ThreadsList/LOAD_THREADS';
  const LOAD_THREADS_SUCCESS = 'reactCommentsDjango/ThreadsList/LOAD_THREADS_SUCCESS';
  const LOAD_THREADS_ERROR = 'reactCommentsDjango/ThreadsList/LOAD_THREADS_ERROR';

  /*
   * ThreadListReducer
   *
   * The reducer takes care of our data. Using actions, we can
   * update our application state. To add a new action,
   * add it to the switch statement in the reducer function
   *
   */

  const initialState = {
    threadsList: false
  };
  /* eslint-disable default-case, no-param-reassign */

  const threadsListReducer = (state = initialState, action) => produce__default['default'](state, draft => {
    switch (action.type) {
      case LOAD_THREADS:
        draft.loading = true;
        draft.error = false;
        draft.threadsList = false;
        break;

      case LOAD_THREADS_SUCCESS:
        draft.threadsList = action.threadsList;
        draft.loading = false;
        break;

      case LOAD_THREADS_ERROR:
        draft.error = action.error;
        draft.loading = false;
        break;
    }
  });

  /**
   * threads list selectors
   */

  const selectThreads = state => state.threads || initialState;

  const makeSelectThreadsList = () => reselect.createSelector(selectThreads, threadListState => threadListState.threadsList);

  const Section = styled__default['default'].section.withConfig({
    displayName: "Section",
    componentId: "sc-13xou8i-0"
  })(["margin:3em auto;&:first-child{margin-top:0;}"]);

  const CenteredSection = styled__default['default'](Section).withConfig({
    displayName: "CenteredSection",
    componentId: "sc-1yf9vry-0"
  })(["text-align:center;"]);

  /*
   * HomePage Messages
   *
   * This contains all the text for the HomePage component.
   */
  const scope = 'boilerplate.containers.HomePage';
  reactIntl.defineMessages({
    threadsList: {
      id: `${scope}.threads`,
      defaultMessage: 'Threads'
    }
  });

  /*
   * App Actions
   *
   * Actions change things in your application
   * Since this boilerplate uses a uni-directional data flow, specifically redux,
   * we have these actions which are the only way your application interacts with
   * your application state. This guarantees that your state is up to date and nobody
   * messes it up weirdly somewhere.
   *
   * To add a new Action:
   * 1) Import your constant
   * 2) Add a function like this:
   *    export function yourAction(var) {
   *        return { type: YOUR_ACTION_CONSTANT, var: var }
   *    }
   */
  /**
   * Load the threads List, this action starts the request saga
   *
   * @return {object} An action object with a type of LOAD_THREADS
   */

  function loadThreads(topicSlug, nextHref) {
    return {
      type: LOAD_THREADS,
      topicSlug,
      nextHref
    };
  }
  /**
   * Dispatched when the threads List are loaded by the request saga
   *
   * @param  {array} threadsList The threads List data
   *
   * @return {object}      An action object with a type of LOAD_THREADS_SUCCESS passing the threadsList
   */

  function threadsListLoaded(threadsList) {
    return {
      type: LOAD_THREADS_SUCCESS,
      threadsList
    };
  }
  /**
   * Dispatched when loading the threadsListitories fails
   *
   * @param  {object} error The error
   *
   * @return {object}       An action object with a type of LOAD_THREADS_ERROR passing the error
   */

  function threadsListLoadingError(error) {
    return {
      type: LOAD_THREADS_ERROR,
      error
    };
  }

  var threadsActionsCreator = /*#__PURE__*/Object.freeze({
    __proto__: null,
    loadThreads: loadThreads,
    threadsListLoaded: threadsListLoaded,
    threadsListLoadingError: threadsListLoadingError
  });

  function getThreads(topicSlug, nextHref) {
    let url;

    if (nextHref) {
      url = nextHref;
    } else {
      url = `${index$1.API_PREFIX}threads/?topic__slug=${topicSlug}`;
    }

    return request.request(url, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      }
    });
  }

  const Api = {
    getThreads
  };

  function* getThreadsList(sagaArgs) {
    const {
      nextHref,
      topicSlug
    } = sagaArgs; // const username = yield select(makeSelectUsername())

    try {
      // Call our request helper (see '../../utils/request')
      // const repos = yield call(request, requestURL)
      const threadsList = yield effects.call(Api.getThreads, topicSlug, nextHref);
      yield effects.put(threadsListLoaded(threadsList));
    } catch (err) {
      yield effects.put(threadsListLoadingError(err));
    }
  } // export function* clearThreadsList() {}

  /**
   * Root saga manages watcher lifecycle
   */

  function* threadsData() {
    // Watches for LOAD_REPOS actions and calls getThreadsList when one comes in.
    // By using `takeLatest` only the result of the latest API call is applied.
    // It returns task descriptor (just like fork) so we can continue execution
    // It will be cancelled automatically on component unmount
    yield effects.takeLatest(LOAD_THREADS, getThreadsList);
  }

  /*
   * ThreadsPage
   *
   * This is the first thing users see of our App, at the '/' route
   */
  const threadsKey = 'threads';
  const topicsKey = 'topics';
  function ThreadsList({
    threadsActions,
    topicsActions,
    match,
    threadsList,
    topic,
    history: _history
  }) {
    index$1.useInjectReducer({
      key: threadsKey,
      reducer: threadsListReducer
    });
    request.useInjectSaga({
      key: threadsKey,
      saga: threadsData
    });
    index$1.useInjectReducer({
      key: topicsKey,
      reducer: saga.topicsListReducer
    });
    request.useInjectSaga({
      key: topicsKey,
      saga: saga.topicsData
    });
    const [threads, setThreads] = React.useState([]);
    const [hasMoreItems, setHasMoreItems] = React.useState(false);
    const [nextHref, setNextHref] = React.useState(null); // const match = useRouteMatch()

    const parentUrlPrefix = match.path.split('/topics')[0];
    let baseName = '';

    if (_history) {
      baseName = _history.createHref({
        pathname: ''
      }).slice(0, -1);
    }

    const breadcrumbSections = [{
      key: 'Topics',
      content: 'Topics',
      href: `${baseName}${parentUrlPrefix}/topics`,
      // link: true,
      onClick: evt => {
        evt.preventDefault(); // inside history do not know about external history basename, so add this

        TopicsListComponent.history.push(`${baseName}${parentUrlPrefix}/topics`);

        if (_history) {
          // parent app history
          _history.push({
            pathname: `${parentUrlPrefix}/topics`
          });
        }
      }
    }];
    React.useEffect(() => {
      topicsActions.loadTopic(match.params.topicSlug); // load threads from server

      threadsActions.loadThreads(match.params.topicSlug);
      return () => {
        // clear threads list while unmount
        threadsActions.threadsListLoaded(false);
      };
    }, []);

    const loadNextPage = () => {
      if (hasMoreItems) {
        // if we call next page setHasMore item false and waiting for a server response
        setHasMoreItems(Boolean(false));
        threadsActions.loadThreads(null, nextHref);
      }
    };

    const onThreadClick = (e, item) => {
      TopicsListComponent.history.push(`${baseName}${parentUrlPrefix}/${topic.slug}/${item.id}/${item.slug}`);

      if (_history) {
        // parent app history
        _history.push({
          pathname: `${parentUrlPrefix}/${topic.slug}/${item.id}/${item.slug}`
        });
      }
    };

    React.useEffect(() => {
      if (threadsList) {
        setThreads([...threads, ...threadsList.results]);
        setHasMoreItems(Boolean(threadsList.next));
        setNextHref(threadsList.next);
      }
    }, [threadsList]);
    let items = [];

    if (threads) {
      items = threads.map(item => /*#__PURE__*/React__default['default'].createElement(ThreadListItem, {
        onClick: e => {
          onThreadClick(e, item);
        },
        key: item.id,
        item: item
      }));
    }

    return /*#__PURE__*/React__default['default'].createElement("article", null, /*#__PURE__*/React__default['default'].createElement(reactHelmet.Helmet, null, /*#__PURE__*/React__default['default'].createElement("title", null, "Threads List"), /*#__PURE__*/React__default['default'].createElement("meta", {
      name: "description",
      content: "React comments Django threads List"
    })), /*#__PURE__*/React__default['default'].createElement(index$2.Breadcrumb, {
      sections: breadcrumbSections
    }), /*#__PURE__*/React__default['default'].createElement("div", null, /*#__PURE__*/React__default['default'].createElement(CenteredSection, null, /*#__PURE__*/React__default['default'].createElement(index$1.H2, null, topic && topic.title)), /*#__PURE__*/React__default['default'].createElement(Section, null, /*#__PURE__*/React__default['default'].createElement(InfiniteScroll__default['default'], {
      pageStart: 0,
      loadMore: loadNextPage,
      hasMore: hasMoreItems // loader={<div key={this.state.nextHref} style={{clear: 'both'}} />} // fix https://github.com/CassetteRocks/react-infinite-scroller/issues/14#issuecomment-225835845

    }, /*#__PURE__*/React__default['default'].createElement(ListGroup__default['default'], null, items), threadsList && threadsList.count === 0 && /*#__PURE__*/React__default['default'].createElement("h4", null, "There are no threads to show")))));
  }
  ThreadsList.propTypes = {
    threadsActions: PropTypes__default['default'].shape({
      loadThreads: PropTypes__default['default'].func.isRequired,
      threadsListLoaded: PropTypes__default['default'].func.isRequired
    }).isRequired,
    topicsActions: PropTypes__default['default'].shape({
      loadTopic: PropTypes__default['default'].func.isRequired
    }).isRequired,
    match: PropTypes__default['default'].object,
    threadsList: PropTypes__default['default'].oneOfType([PropTypes__default['default'].object, PropTypes__default['default'].bool]),
    topic: PropTypes__default['default'].oneOfType([PropTypes__default['default'].object, PropTypes__default['default'].bool])
  };
  const mapStateToProps = reselect.createStructuredSelector({
    threadsList: makeSelectThreadsList(),
    topic: saga.makeSelectTopic() // username: makeSelectUsername(),
    // loading: makeSelectLoading(),
    // error: makeSelectError(),

  });
  function mapDispatchToProps(dispatch) {
    return {
      threadsActions: redux.bindActionCreators(threadsActionsCreator, dispatch),
      topicsActions: redux.bindActionCreators(saga.loadTopicsActionsCreator, dispatch)
    };
  }
  const withConnect = reactRedux.connect(mapStateToProps, mapDispatchToProps);
  var index = redux.compose(withConnect, React.memo)(ThreadsList);

  exports.ThreadsList = ThreadsList;
  exports.default = index;
  exports.mapDispatchToProps = mapDispatchToProps;

});
//# sourceMappingURL=index-5b5af8d7.js.map
