import Component from 'ember-component';
import computed from 'ember-computed';
import hbs from 'htmlbars-inline-precompile';
import { trySet } from 'ember-metal/set';
import validateEvent, { MIME_TYPES } from 'web-client/utilities/events/validate-event';
import { readFile as getDataURL } from 'web-client/utilities/html5-loader';

export default Component.extend({
  tagName: 'form',

  // Injected property
  onDidSave() {},
  getDataURL,

  isSaving: false,
  isGamePending: false,
  previewURL: '',
  acceptedMimeTypes: MIME_TYPES,
  gameName: null,

  layout: hbs`
    {{yield (hash
      didReceiveErrorResponse=didReceiveErrorResponse
      isDisabled=isDisabled
      validation=validation
      onGameSelect=(action 'onGameSelect')
      onGamePending=(action 'onGamePending')
      onImagePicked=(action 'onImagePicked')
      previewURL=previewURL
      gameName=gameName
      acceptedMimeTypes=acceptedMimeTypes
    )}}
  `,

  validation: computed(
    `event.{startTime,endTime,gameId}`,
    'gameName',
    'imageFile',
    function() {
      return validateEvent({
        startTime: this.get('event.startTime'),
        endTime: this.get('event.endTime'),
        gameName: this.get('gameName'),
        gameId: this.get('event.gameId'),
        imageFile: this.get('imageFile')
      });
    }
  ),

  isDisabled: computed.or('isSaving', 'isGamePending', 'validation.hasErrors'),

  submit(browserEvent) {
    browserEvent.preventDefault();

    this.set('isSaving', true);

    this.get('event').save().then(() => {
      trySet(this, 'didReceiveErrorResponse', false);
      this.get('onDidSave')();
    }).catch(error => {
      if (error.status && error.status >= 400) {
        trySet(this, 'didReceiveErrorResponse', true);
      } else {
        throw error;
      }
    }).finally(() => {
      trySet(this, 'isSaving', false);
    });
  },

  actions: {
    onGameSelect(game) {
      this.set('gameName', game.name);
      this.set('event.gameId', game.id);
      this.set('isGamePending', false);
    },

    onGamePending() {
      this.set('isGamePending', true);
    },

    onImagePicked(file) {
      this.set('imageFile', file);

      if (this.get('validation.warnings.imageFile')) {
        return;
      }

      this.getDataURL(file).then((url) => {
        trySet(this, 'previewURL', url);
      });
    }
  }
});
