import sortBy from "../sorting/sortBy.js";
import { demAltPalettes, gopAltPalettes } from './electionPalettes';
const getAltCandidatePalettes = function getAltCandidatePalettes(candidates) {
  const sortedCandidates = sortBy(candidates, [{
    comparison: 'editorialOrder',
    direction: 'asc',
    nullFirst: false
  }, {
    comparison: 'ballotOrder',
    direction: 'asc',
    nullFirst: false
  }, {
    comparison: 'shortName',
    direction: 'asc',
    nullFirst: false
  }, {
    comparison: 'id',
    direction: 'asc'
  }]);
  const getPaletteOrder = order => {
    const set = new Set(order);
    const iterator = set[Symbol.iterator]();
    return {
      set,
      iterator
    };
  };
  const fallbacks = ['fallback-alt01', 'fallback-alt02', 'fallback-alt03', 'fallback-alt04', 'fallback-alt05'];
  const demFirst = [...demAltPalettes, ...gopAltPalettes, ...fallbacks];
  const gopFirst = [...gopAltPalettes, ...demAltPalettes, ...fallbacks];
  const paletteOrderByParty = {
    dem: getPaletteOrder(demFirst),
    gop: getPaletteOrder(gopFirst),
    independent: getPaletteOrder(gopFirst),
    'other-party': getPaletteOrder(demFirst)
  };
  const allocateColor = color => {
    Object.values(paletteOrderByParty).forEach(order => {
      order.set.delete(color);
    });
    return color;
  };

  // Pre-allocate any custom colors that are set
  sortedCandidates.forEach(candidate => {
    if (!candidate.customColor) return;
    allocateColor(candidate.customColor);
  });
  const colors = sortedCandidates.map(candidate => {
    // Use custom color whenever it's set
    if (candidate.customColor) {
      return [candidate.id, candidate.customColor];
    }

    // Get the order based on their party. Fallback if none
    const order = paletteOrderByParty[candidate.party];
    if (!order) return [candidate.id, 'fallback'];

    // Allocate next free value in order. Fallback if done
    const iterValue = order.iterator.next();
    if (iterValue.done) return [candidate.id, 'fallback'];
    return [candidate.id, allocateColor(iterValue.value)];
  });
  return Object.fromEntries(colors);
};
export default getAltCandidatePalettes;