import { useParams } from 'react-router-dom';
import Card from './card';
import Error from './error';
import MultiFetcher from '../shared/fetches/multi-fetcher';
import { fetchNextCard } from '../../redux/actions/card';
import { fetchChapter } from '../../redux/actions/chapter';

function CardsContainer() {
  const { chapterId, cardType } = useParams();
  const urlSearchParams = new URLSearchParams(location.search);
  const priority = urlSearchParams.get('priority');
  const rateType = urlSearchParams.get('rate-type');
  const minRate = rateType ? { starred: 1, active: 0 }[rateType] : null;

  return (
    <MultiFetcher
      actions={[
        fetchNextCard.bind(null, chapterId, cardType, priority, minRate),
        fetchChapter.bind(null, chapterId, priority, minRate)
      ]}
      stateSelectors={{
        card: state => state.card,
        chapter: state => state.chapter
      }}
      renderError={error => <Error error={error} />}
    >
      {({ card, chapter }) => <Card card={card} chapter={chapter} />}
    </MultiFetcher>
  );
}

export default CardsContainer;
