import { selectorFamily } from 'recoil';
import cycleCandidateMetadataAtom from '../atoms/cycleCandidateMetadata';
import multiSourceData from './multiSourceData';
const getData = (key, source) => {
  if (source.config.type === 'cycle-candidate-collection') {
    return source.data[key];
  }
  return source.data;
};

/**
 * 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 cycleCandidateMetadata = selectorFamily({
  key: 'election.selectors.cycleCandidateMetadata',
  get: key => ({
    get
  }) => {
    const atom = cycleCandidateMetadataAtom(key);
    const source = get(multiSourceData(atom.key));
    if (!source) return undefined;
    return {
      data: getData(key, source),
      source
    };
  }
});
export default cycleCandidateMetadata;