import ensureDate from './ensureDate';
import segments from './segments';
const formatDate = function formatDate(dateInput, options = {}) {
  const {
    format,
    timeZone
  } = options;
  if (!dateInput) {
    return undefined;
  }
  const date = ensureDate(dateInput);
  const fmt = opts => date.toLocaleString('en-US', {
    timeZone,
    ...opts
  });
  const get = string => formatDate(dateInput, {
    ...options,
    format: string
  });
  const resolveSegment = segment => {
    if (typeof segment === 'object') return fmt(segment);
    return segment({
      fmt,
      get,
      d: date
    });
  };
  if (segments[format]) {
    return resolveSegment(segments[format]);
  }
  let formattedString = '';
  let token = '';
  let inToken = false;
  format.split('').forEach(letter => {
    if (letter === '{' && !inToken) {
      inToken = true;
      token = '';
    } else if (letter === '}' && inToken) {
      const value = segments[token] ? resolveSegment(segments[token]) : `{${token}}`;
      formattedString += value;
      inToken = false;
      token = '';
    } else if (inToken) {
      token += letter;
    } else {
      formattedString += letter;
    }
  });
  return formattedString;
};
export default formatDate;