import { selectorFamily } from 'recoil';
import contestSummaryResults from './contestSummaryResults';
import contestCountyResults from './contestCountyResults';

/**
 * Select a results object for a contest. This can either be a summary-level
 * results object when given a contest ID, or a county-level results object
 * when given a reporting unit ID.
 */
const results = selectorFamily({
  key: 'election.selectors.results',
  get: key => ({
    get
  }) => {
    if (!key) return undefined;
    if (key.startsWith('contest')) return get(contestSummaryResults(key));
    const [, contestId] = key.split('::');
    const counties = get(contestCountyResults(contestId));
    if (!counties) return undefined;
    const county = counties.data.counties.find(ru => ru.id === key);
    return {
      ...counties,
      data: county
    };
  }
});
export default results;