import { selectorFamily } from 'recoil';
import lodashGet from 'lodash/get';
import contestSummaryResultsAtom from '../atoms/contestSummaryResults';
import contestCallEvents from './contestCallEvents';
import multiSourceData from './multiSourceData';
const getData = (key, source) => {
  if (source.config.type === 'summary-collection') {
    return source.data.contestsById[key];
  }
  return source.data;
};

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