import { selectorFamily } from 'recoil';
import getAltCandidatePalettes from "../../../utils/colors/getAltCandidatePalettes.js";
import getMostRecentSource from '../utils/getMostRecentSource';
import contestMetadata from './contestMetadata';
import contestCandidatesMetadata from './contestCandidatesMetadata';
const getData = (contest, candidates) => {
  if (contest.isBallot) {
    return Object.fromEntries(candidates.map(c => [c.id, c.polarity ? 'ballot-yes' : 'ballot-no']));
  }
  if (contest.contestType === 'general') {
    const supportedParties = new Set(['dem', 'gop']);
    return Object.fromEntries(candidates.map(c => [c.id, supportedParties.has(c.party) ? c.party : 'fallback']));
  }
  return getAltCandidatePalettes(candidates);
};

/**
 * Select the color assignments of each candidate in a contest.
 */
const contestCandidateColors = selectorFamily({
  key: 'election.selectors.contestCandidateColors',
  get: key => ({
    get
  }) => {
    const contest = get(contestMetadata(key));
    const candidates = get(contestCandidatesMetadata(key));
    if (!contest || !candidates) return undefined;
    return {
      data: getData(contest.data, candidates.data),
      source: getMostRecentSource([contest.source, candidates.source])
    };
  }
});
export default contestCandidateColors;