import { useMemo } from 'react';
import { useRecoilState } from 'recoil';
import { favoriteContests } from "../../../atoms/election/index.js";

/**
 * Use the whole favorited contests store object with information about the
 * favorited contests and functions to add/remove individual contests.
 */
const useFavoriteContests = function useFavoriteContests() {
  const [contests, setContests] = useRecoilState(favoriteContests('default'));
  return useMemo(() => {
    const contestSet = new Set(contests);
    return {
      favoriteContests: contests,
      isContestFavorite: contestId => contestSet.has(contestId),
      addFavoriteContest: contestId => {
        if (contestSet.has(contestId)) return;
        setContests([...contests, contestId]);
      },
      removeFavoriteContest: contestId => {
        if (!contestSet.has(contestId)) return;
        setContests(contests.filter(id => id !== contestId));
      }
    };
  }, [contests, setContests]);
};
export default useFavoriteContests;