import contestCandidateIds from '../../atoms/contestCandidateIds';
const getContestCandidates = ({
  type,
  data
}) => {
  if (!data) return new Map();
  if (type === 'candidate') {
    return new Map([[data.contestId, data.id]]);
  }
  if (type === 'candidate-collection') {
    return Object.entries(data).reduce((map, [id, candidate]) => {
      const {
        contestId
      } = candidate;
      if (!map.has(contestId)) map.set(contestId, []);
      map.get(contestId).push(id);
      return map;
    }, new Map());
  }
  if (type === 'combined-metadata') {
    return new Map([[data.contest.id, Object.keys(data.candidates)]]);
  }
  if (type === 'combined-metadata-collection') {
    return new Map(data.map(meta => [meta.contest.id, Object.keys(meta.candidates)]));
  }
  return undefined;
};
const updateCrossTables = function updateCrossTables({
  set,
  source
}) {
  const {
    config: {
      type
    },
    data
  } = source;
  const contestCandidates = getContestCandidates({
    type,
    data
  });
  if (!contestCandidates) return;
  [...contestCandidates].forEach(([contestId, candidateIds]) => {
    set(contestCandidateIds(contestId), oldCandidates => [...new Set([...oldCandidates, ...candidateIds])]);
  });
};
export default updateCrossTables;