import { selectorFamily } from 'recoil';
import lodashGet from 'lodash/get';
import contestSummaryCollection from '../atoms/contestSummaryCollection';
import contestMetadata from './contestMetadata';
import contestCandidatesMetadata from './contestCandidatesMetadata';
import multiSourceData from './multiSourceData';
const contestCollectionMetadata = selectorFamily({
  key: 'election.selectors.contestCollectionMetadata',
  get: key => ({
    get
  }) => {
    const atom = contestSummaryCollection(key);
    const source = get(multiSourceData(atom.key));
    if (!source) return undefined;
    const contestEntries = source.data.contests.map(contestId => {
      const contestMeta = lodashGet(get(contestMetadata(contestId)), 'data', {});
      const candidates = lodashGet(get(contestCandidatesMetadata(contestId)), 'data', []);
      const candidateEntries = candidates.map(cand => [cand.id, cand]);
      return [contestId, {
        ...contestMeta,
        candidates: Object.fromEntries(candidateEntries)
      }];
    });
    return {
      data: Object.fromEntries(contestEntries),
      source
    };
  }
});
export default contestCollectionMetadata;