import sortBy from "../../sorting/sortBy.js";

/**
 * Get the canonical status of a county based on its results. A county can
 * be in any of the following states:
 *
 * - a single candidate "won" the county with finalized results,
 * - a single candidate is clearly leading in the county with a sufficient
 *   amount of the vote tabulated, or
 * - there is no clear leader
 *
 * @param {CountyResult} county
 *   The results object of a single county
 *
 * @returns {object} status
 * @returns {'unclear'|'leader'|'winner'} status.status
 * @returns {string} [candidateId]
 */
const getCountyStatus = function getCountyStatus(county) {
  const clarityThreshold = 0.10; // TODO
  const noClearLeader = {
    status: 'unclear',
    candidateId: undefined
  };
  if (!county) return noClearLeader;
  const {
    progress: {
      pct = 0
    },
    results = []
  } = county;
  if (pct < clarityThreshold) return noClearLeader;
  if (results.length < 2) return noClearLeader;
  const [first, second] = sortBy(results, [{
    comparison: 'votes',
    direction: 'desc'
  }, 'id']);
  const isTied = first.votes === second.votes;
  if (isTied) return noClearLeader;
  const isFinal = pct === 1;
  return {
    status: isFinal ? 'winner' : 'leader',
    candidateId: first.id
  };
};
export default getCountyStatus;