import Component from 'ember-component';
import moment from 'moment';
import { convertTimeStringToMoment } from 'web-client/components/time-picker';
import roundTime from 'web-client/utilities/events/round-time';

export default Component.extend({
  // Injected properties
  onStartChange() {},
  onEndChange() {},
  start: null,
  end: null,

  actions: {
    setStartDate(date) {
      let nextStart = withDateValues(this.get('start'), date);
      this.get('onStartChange')(nextStart);
    },

    setEndDate(date) {
      let nextEnd = withDateValues(this.get('end'), date);
      this.get('onEndChange')(nextEnd);
    },

    setStartTime(timeString) {
      let date = convertTimeStringToMoment(timeString);
      let nextStart = roundTime(withTimeValues(this.get('start'), date));
      this.get('onStartChange')(nextStart);
    },

    setEndTime(timeString) {
      let date = convertTimeStringToMoment(timeString);
      let nextEnd = roundTime(withTimeValues(this.get('end'), date));
      this.get('onEndChange')(nextEnd);
    }
  }
});

// Copy the baseDate and only change the year, month, and day.
function withDateValues(baseDate, newDate) {
  let newMoment = moment(newDate);
  return moment(baseDate).set({
    year: newMoment.year(),
    month: newMoment.month(),
    date: newMoment.date()
  }).toDate();
}

// Copy the baseDate, update the hours and minutes, clear the seconds and
// milliseconds.
function withTimeValues(baseDate, newDate) {
  let newMoment = moment(newDate);
  return moment(baseDate).set({
    hours: newMoment.hours(),
    minutes: newMoment.minutes(),
    seconds: 0,
    milliseconds: 0
  }).toDate();
}
