import { useMemo } from 'react';
import { useContestCollectionMetadata } from "../../../hooks/election/index.js";
import sortBy from "../../../utils/sorting/sortBy.js";

/**
 * @param {object} opts
 * @param {{ district: string, party: string }[]} opts.annotations
 * @param {string} opts.collectionId
 */
const useAnnotatedContests = function useAnnotatedContests(opts) {
  const {
    collectionId,
    annotations
  } = opts;
  const collectionContests = useContestCollectionMetadata(collectionId);
  return useMemo(() => {
    if (!collectionContests) return [];
    const meta = Object.values(collectionContests);
    const collectionMap = meta.reduce((map, contest) => {
      const {
        id,
        districtNumber,
        party
      } = contest;
      const key = `${districtNumber}-${party}`;
      if (map.has(key)) {
        // eslint-disable-next-line no-console
        console.warn('Multiple contests found for same district and party' + ` (${districtNumber} ${party})`);
      }
      map.set(key, id);
      return map;
    }, new Map());
    const contests = annotations.map(annotation => {
      const {
        district,
        party,
        reporterNote
      } = annotation;
      const key = `${district}-${party}`;
      const contestId = collectionMap.get(key);
      if (!contestId) return undefined;
      return {
        contestId,
        reporterNote
      };
    }).filter(Boolean);
    return sortBy(contests, [{
      comparison: 'reporterNote.lastUpdated',
      direction: 'desc'
    }, 'contestId']);
  }, [collectionContests, annotations]);
};
export default useAnnotatedContests;