import moment from 'moment';

/**
 * This function rounds time to the nearest 30 minute point. This is specific
 * to the rules of Events which must be in 30 minute increments. Future
 * travelers are encouraged to make this function more flexible by adding more
 * arguments.
 *
 * If a moment object is sent this function will also return a moment object.
 * Otherwise this function will return a Date object.
 *
 * @param date - a date to use as the source of a new rounded date
 * @return a new date that has been rounded
 */
export default function roundTime(date) {
  let inputWasMoment = moment.isMoment(date);
  let m = moment(date);
  let minutes = m.minutes();

  if (minutes > 14 && minutes < 45) {
    m.minutes(30);
  } else if (minutes < 15) {
    m.minutes(0);
  } else {
    m.minutes(0).add(1, 'hour');
  }

  m.set({ seconds: 0, milliseconds: 0 });

  return inputWasMoment ? m : m.toDate();
}
