import Component from 'ember-component';
import moment from 'moment';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';
import { isFunction } from 'web-client/utilities/type-of';

export const PUBLISH_STRATEGIES = [{
  value: 'public',
  label: 'Published',
  description: "Your video will be public."
}, {
  value: 'private',
  label: 'Unpublished',
  description: "Your video will only be viewable by you."
}, {
  value: 'scheduled',
  label: 'Scheduled',
  description: "Your video will be public on the scheduled date."
}];

export default Component.extend({
  init() {
    this._super(...arguments);
    this.minDate = new Date();

    if (this.onPublishStrategyChanged) {
      assert(`onPublishStrategyChanged must be a function`, isFunction(this.onPublishStrategyChanged));
    }
  },

  publishStrategies: PUBLISH_STRATEGIES,

  publishDescription: computed.alias('currentPublishStrategy.description'),

  currentPublishStrategy: computed('video.viewable', 'video.isScheduled', function() {
    let viewable = this.get('video.isScheduled') ? 'scheduled' : this.get('video.viewable');
    let publishStrategy = PUBLISH_STRATEGIES.find((ps) => ps.value === viewable);

    if (this.onPublishStrategyChanged) {
      this.onPublishStrategyChanged(publishStrategy);
    }
    return publishStrategy;
  }),

  didRender() {
    this.set('pikadayContainer', this.$('#pikaday-container')[0]);
  },

  actions: {
    setViewableAtDate(date) {
      let viewableAtDate = moment(date);
      let viewableAt = moment(this.get('video.viewableAt'));

      if (viewableAtDate.isValid()) {
        viewableAt.year(viewableAtDate.year());
        viewableAt.month(viewableAtDate.month());
        viewableAt.date(viewableAtDate.date());
      }

      this.set('video.viewableAt', viewableAt.toDate());
    },

    setViewableAtTime(time) {
      let viewableAtTime = moment(time, 'h:mma');
      let viewableAt = moment(this.get('video.viewableAt'));

      if (viewableAtTime.isValid()) {
        viewableAt.hours(viewableAtTime.hours());
        viewableAt.minutes(viewableAtTime.minutes());
        viewableAt.seconds(viewableAtTime.seconds());
      }

      this.set('video.viewableAt', viewableAt.toDate());
    },

    setPublishStrategy(strategy) {
      let viewable = strategy;
      let viewableAt;

      if (strategy === 'scheduled') {
        viewable = 'private';
        viewableAt = new Date();
      } else {
        viewableAt = null;
      }

      this.get('video').setProperties({ viewable, viewableAt });
    }
  }
});
