import { selectorFamily, waitForAll } from 'recoil';
import contestCandidateIds from '../atoms/contestCandidateIds';
import getMostRecentSource from '../utils/getMostRecentSource';
import compoundCandidateMetadata from './compoundCandidateMetadata';

/**
 * Select the candidate metadata for all of a contest's candidates.
 */
const contestCandidatesMetadata = selectorFamily({
  key: 'election.selectors.contestCandidatesMetadata',
  get: key => ({
    get
  }) => {
    const candidateIds = get(contestCandidateIds(key));
    const candidates = get(waitForAll(candidateIds.map(id => compoundCandidateMetadata(id))));
    const contestCandidates = candidates.filter(candidate => candidate.data.contestId === key);
    return {
      data: contestCandidates.map(({
        data
      }) => data),
      source: getMostRecentSource(contestCandidates.map(({
        source
      }) => source))
    };
  }
});
export default contestCandidatesMetadata;