import { selectorFamily } from 'recoil';
import lodashGet from 'lodash/get';
import contestSummaryResultsAtom from '../atoms/contestSummaryResults';
import { formattedContestCallEventsFromCalls } from '../utils';
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 data = getData(key, source);
    const calls = formattedContestCallEventsFromCalls(key, lodashGet(data, 'calls', []));
    return {
      data: {
        ...data,
        ...calls
      },
      source
    };
  }
});
export default contestSummaryResults;