import Component from 'ember-component';
import getFileFromEvent from 'web-client/utilities/get-file-from-event';

export const IS_HOVERING_CLASS = 'drop-zone--active';
export const UPLOADING_CLASS = 'drop-zone--uploading';

export default Component.extend({
  classNameBindings: [`isHovering:${IS_HOVERING_CLASS}`, `isUploading:${UPLOADING_CLASS}`],
  isHovering: false,
  isUploading: false,

  // Default attr
  onFileDrop() {},

  didInsertElement() {
    this._super(...arguments);
    this.$().attr('data-test-file-drop-zone', '');
  },

  dragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    this.set('isHovering', false);
  },

  dragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    this.set('isHovering', true);
  },

  drop(e) {
    e.preventDefault();
    e.stopPropagation();
    let file = e.dataTransfer.files[0];
    this.get('onFileDrop')(file);
    this.set('isHovering', false);
  },

  click(e) {
    let input = this.$('input');

    // Break if this is the click that we just triggered on the hidden input.
    if (e.target === input[0]) {
      return;
    }

    // Forward click to the input to open the file picker
    this.$('input').click();
  },

  actions: {
    onFileChange(e) {
      this.get('onFileDrop')(getFileFromEvent(e));
      this.$('form')[0].reset();
    }
  }
});
