import PropTypes from 'prop-types';
import { useResults } from "../../../hooks/election/index.js";
import { getFormattedAggregateCandidateVotes } from "../../../utils/election/index.js";
import customizable from "../../../utils/css/customizable.js";
import DataAnimation from '../DataAnimation';

/**
 * Add up all the votes received by a set of candidates and render the
 * formatted total either as a raw vote count or as a percentage of the total
 * votes tabulated in the contest.
 *
 * This component also adds the `int-style-AggregateCandidateVotesPctSign`
 * class for styling the percent sign.
 */
const AggregateCandidateVotes = function AggregateCandidateVotes(props) {
  const {
    id,
    candidateIds,
    format,
    minimumFractionDigits,
    maximumFractionDigits
  } = props;
  const results = useResults(id);
  const votes = getFormattedAggregateCandidateVotes(results, candidateIds, {
    format,
    minimumFractionDigits,
    maximumFractionDigits
  });
  if (format !== 'percent') {
    return <DataAnimation trigger={votes}>
        {votes}
      </DataAnimation>;
  }
  const number = votes.replace('%', '');
  return <>
      <DataAnimation trigger={number}>
        {number}
      </DataAnimation>
      <span className={customizable('AggregateCandidateVotesPctSign')}>
        %
      </span>
    </>;
};
AggregateCandidateVotes.defaultProps = {
  candidateIds: undefined,
  format: 'number',
  minimumFractionDigits: undefined,
  maximumFractionDigits: 1
};
AggregateCandidateVotes.propTypes = {
  /**
   * The ID of the results to use
   */
  id: PropTypes.string.isRequired,
  /**
   * The IDs of the candidates to aggregate
   */
  candidateIds: PropTypes.arrayOf(PropTypes.string),
  /**
   * The format to use for the aggregation
   */
  format: PropTypes.oneOf(['number', 'percent', 'sentence']),
  /**
   * The minimum number of decimal places to render
   */
  minimumFractionDigits: PropTypes.number,
  /**
   * The maximum number of decimal places to render
   */
  maximumFractionDigits: PropTypes.number
};
export default AggregateCandidateVotes;