import { capfirst } from 'journalize';
import { statesByFips } from '../constants/states';

/**
 * Function to format a state's name based on its FIPS code
 *
 * @param {string} fipsCode
 *   A state's FIPS code
 * @param {Object} [options]
 *   Additional configuration options:
 *   - `format`: The format of the name (either `abbr`, `ap_abbr`, `sentence` or `name`,
 *     the default being `name`)
 *   - `possessive`: Set to `true` to make the name possessive.
 *   - `capitalized`: Set to `true` to capitalize the first word in the `sentence format`.
 *      Most names will always be capitalized, but some, like "the Northern Mariana Islands"
 *      need a little help when they are starting a sentence.
 * @returns {string}
 */
const getStateName = function getStateName(fipsCode, opts = {}) {
  const {
    format = 'name',
    possessive = false,
    capitalized = false
  } = opts;
  const state = statesByFips[fipsCode];
  if (!state) {
    return undefined;
  }
  const stateFormats = {
    abbr: state.abbr,
    ap_abbr: state.ap_abbr,
    name: state.name,
    sentence: state.sentence
  };
  const stateName = stateFormats[format];
  if (!stateName) {
    return undefined;
  }
  let nameString = stateName;
  if (possessive) {
    const possessiveStateSuffix = stateName.endsWith('s') ? '’' : '’s';
    nameString = `${stateName}${possessiveStateSuffix}`;
  }
  if (capitalized) {
    return capfirst(nameString);
  }
  return nameString;
};
export default getStateName;