/** @module utils/DateUtils/extractTimeParts */
import formatTime from './formatTime';

/**
 * Extracts the hours, minutes, and optional time period from
 * a date time.
 *
 * @param {function} DateTimeFormat the DateTimeFormat function to use.
 * @param {string|string[]} locales the locales to use.
 * @param {Boolean} showSeconds boolean if seconds should be extracted
 * @param {Date} time the time to extract from.
 * @return {Object} an object of { hours, minutes, timePeriod }
 */
export default function extractTimeParts(DateTimeFormat, locales, showSeconds, time) {
  var hours = void 0;
  var minutes = void 0;
  var seconds = void 0;
  var minuteSeparator = void 0;
  var secondSeparator = void 0;
  var remaining = void 0;
  var formatted = formatTime(DateTimeFormat, locales, showSeconds, time);
  // IE does not like lookaheads or splitting on [^0-9]
  // it will include the non-printable characters..

  if (showSeconds === true) {
    var _formatted$match = formatted.match(/[0-9]+/g);

    hours = _formatted$match[0];
    minutes = _formatted$match[1];
    seconds = _formatted$match[2];

    var _formatted$match2 = formatted.match(/[ ,.:A-z]+/g);

    minuteSeparator = _formatted$match2[0];
    secondSeparator = _formatted$match2[1];
    remaining = _formatted$match2.slice(2);
  } else {
    var _formatted$match3 = formatted.match(/[0-9]+/g);

    hours = _formatted$match3[0];
    minutes = _formatted$match3[1];

    var _formatted$match4 = formatted.match(/[ ,.:A-z]+/g);

    minuteSeparator = _formatted$match4[0];
    remaining = _formatted$match4.slice(1);
  }

  var timePeriod = void 0;
  if (remaining && remaining.length) {
    timePeriod = remaining.join('').trim();
  }

  if (showSeconds === true) {
    return {
      hours: hours,
      minutes: minuteSeparator + minutes,
      seconds: secondSeparator + seconds,
      timePeriod: timePeriod
    };
  }

  return {
    hours: hours,
    minutes: minuteSeparator + minutes,
    timePeriod: timePeriod
  };
}