import { selectorFamily } from 'recoil';
import candidateMetadataAtom from '../atoms/candidateMetadata';
import multiSourceData from './multiSourceData';
const getData = (key, source) => {
  if (source.config.type === 'candidate-collection') {
    return source.data[key];
  }
  if (source.config.type === 'combined-metadata') {
    return source.data.candidates[key];
  }
  if (source.config.type === 'combined-metadata-collection') {
    const contest = source.data.find(d => key in d.candidates);
    return contest && contest[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 candidateMetadata = selectorFamily({
  key: 'election.selectors.candidateMetadata',
  get: key => ({
    get
  }) => {
    const atom = candidateMetadataAtom(key);
    const source = get(multiSourceData(atom.key));
    if (!source) return undefined;
    return {
      data: getData(key, source),
      source
    };
  }
});
export default candidateMetadata;