import { selectorFamily } from 'recoil';
import contestMetadataAtom from '../atoms/contestMetadata';
import multiSourceData from './multiSourceData';
const getData = (key, source) => {
  if (source.config.type === 'metadata-collection') {
    return source.data[key];
  }
  if (source.config.type === 'combined-metadata') {
    return source.data.contest;
  }
  if (source.config.type === 'combined-metadata-collection') {
    return source.data.find(d => d.contest.id === key);
  }
  return source.data;
};

/**
 * Contest metadata can either be hydrated by a metadata collection or
 * a single-contest metadata file.
 */
const contestMetadata = selectorFamily({
  key: 'election.selectors.contestMetadata',
  get: key => ({
    get
  }) => {
    const atom = contestMetadataAtom(key);
    const source = get(multiSourceData(atom.key));
    if (!source) return undefined;
    return {
      data: getData(key, source),
      source
    };
  }
});
export default contestMetadata;