import Controller from 'ember-controller';
import injectService from 'ember-service/inject';
import moment from 'moment';
import roundTime from 'web-client/utilities/events/round-time';
import requestIdleCallback from 'web-client/utilities/request-idle-callback';
import withMomentTimezoneData from 'web-client/utilities/with-moment-timezone-data';

export default Controller.extend({
  store: injectService(),

  // This value must be false and not null because modal-dialog assigns special
  // meaning to showModal=null... which means show the modal :/
  selectedEvent: false,

  init() {
    this._super(...arguments);

    // Prime the moment timezone data so that hopefully users won't
    // see a delay when they click the create button.
    requestIdleCallback(withMomentTimezoneData);
  },

  actions: {
    createEvent() {
      withMomentTimezoneData().then(tz => {
        if (this.isDestroyed) { return; }

        let newEvent = this.get('store').createRecord('event', {
          channel: this.get('model'),

          /*
          Default event time range is:
              - tomorrow
              - about the same time as today
              - an hour long.
          */
          startTime: roundTime(moment().add({ days: 1 })).toDate(),
          endTime: roundTime(moment().add({ days: 1, hours: 1 })).toDate(),
          timeZoneId: tz.guess()
        });

        this.set('selectedEvent', newEvent);
      });
    },

    cancelEdit() {
      this.get('selectedEvent').rollbackAttributes();
      this.set('selectedEvent', false);
    },

    close() {
      this.set('selectedEvent', false);
    }
  }
});
