import get from 'lodash/get';
import getStateName from "../getStateName/index.js";
import getOfficeName from "../getOfficeName/index.js";
import getCandidateName from "../getCandidateName/index.js";
import autohed from './autohed';
const raceCall = function raceCall(opts) {
  const {
    call,
    contestMetadata,
    candidateMetadata
  } = opts;
  const fips = get(contestMetadata, 'stateFips');
  const stateName = getStateName(fips);
  const stateAbbr = getStateName(fips, {
    format: 'abbr'
  });
  const seat = get(contestMetadata, 'districtNumber', '00');
  const district = `${stateAbbr}-${seat}`;
  const raceName = get(contestMetadata, 'name');
  const candidateName = getCandidateName(candidateMetadata);
  const office = get(contestMetadata, 'office');
  const isRunoff = get(call, 'type') === 'runoff';
  const isWinner = get(call, 'type') === 'winner';
  const officeBaseName = getOfficeName(office);
  const spec = get(contestMetadata, 'isSpecial', false) ? ' special' : '';
  const officeName = `${officeBaseName}${spec}`;
  if (isRunoff) {
    if (office === 'president') {
      return autohed`${candidateName} advances to runoff in ${stateName} presidential election`;
    }
    if (office === 'house') {
      return autohed`${candidateName} advances to runoff in ${district}`;
    }
    if (office === 'question') {
      return autohed`${raceName} goes to runoff in ${stateName}`;
    }
    return autohed`${candidateName} advances to runoff in ${stateName} ${officeName} election`;
  }
  if (isWinner) {
    const holdingParty = get(contestMetadata, 'holdingParty');
    const winParty = get(candidateMetadata, 'caucusesWithParty', get(candidateMetadata, 'party'));
    const isFlip = ['dem', 'gop'].includes(winParty) && holdingParty && holdingParty !== winParty;
    const verbs = isFlip ? 'flips' : 'wins';
    if (office === 'president') {
      return autohed`${candidateName} ${verbs} ${stateName}`;
    }
    if (office === 'house') {
      return autohed`${candidateName} ${verbs} ${district}`;
    }
    if (office === 'question') {
      const winnerParty = get(candidateMetadata, 'party');
      if (winnerParty === 'yes') {
        return autohed`${raceName} passes in ${stateName}`;
      }
      if (winnerParty === 'no') {
        return autohed`${raceName} fails to pass in ${stateName}`;
      }
      return undefined;
    }
    if (office === 'senate') {
      return autohed`${candidateName} ${verbs} ${stateName} Senate seat`;
    }
    return autohed`${candidateName} elected ${officeName} of ${stateName}`;
  }
  return undefined;
};
export default raceCall;