import { ordinal } from 'journalize';
import getStateName from '../getStateName';

/**
 * Get a district's name in a particular format from a combination of FIPS code and district number.
 * @param {string} options.districtNumber
 *   A district's number
 * @param {string} options.stateFips
 *   A state FIPS code
 * @param {Object} [options]
 *   Additional configuration options:
 *   - `format`: The format of the name (either `full`, `abbr` or `ordinal`.
 *   - `customName`: A custom name that overrides formatting

 * @returns {string}
 */
const getDistrictName = function getDistrictName(opts) {
  const {
    format = 'long',
    customName = undefined,
    districtNumber,
    stateFips
  } = opts;
  if (!districtNumber || !stateFips) {
    return undefined;
  }

  // TODO: should a custom name really override for all formats?
  if (customName) {
    return customName;
  }
  const isAtLarge = districtNumber === '00';

  // e.g., "1st", "00"
  if (format === 'ordinal') {
    return isAtLarge ? districtNumber : ordinal(parseInt(districtNumber, 10));
  }

  // e.g., "NM-01", "AK-AL"
  if (format === 'abbr') {
    const district = isAtLarge ? 'AL' : districtNumber;
    const stateName = getStateName(stateFips, {
      format: 'abbr'
    });
    return `${stateName}-${district}`;
  }

  // Default full format, e.g., "New Mexico's 1st district", "Alaska's At-large district"
  const stateName = getStateName(stateFips, {
    format: 'name',
    possessive: true
  });
  const districtName = isAtLarge ? 'At-large' : ordinal(parseInt(districtNumber, 10));
  return `${stateName} ${districtName} district`;
};
export default getDistrictName;