import { selectorFamily } from 'recoil';
import combinedMetadata from '../atoms/combinedMetadata';

/**
 * Candidate metadata can either be hydrated by a candidate collection or
 * a single-candidate metadata file. (In practice, this is always hydrated by
 * a candidate collection.)
 */
const candidateMetadata = selectorFamily({
  key: 'election.selectors.candidateMetadata',
  get: key => ({
    get
  }) => {
    if (!key) return undefined;
    const contestId = key.split('::')[1];
    const source = get(combinedMetadata(contestId));
    if (!source || !source.data) return undefined;
    return {
      metadata: source.metadata,
      data: source.data.candidates[key]
    };
  }
});
export default candidateMetadata;