/* globals loadImage */

import $ from 'jquery';
import Component from 'ember-component';

const THUMBNAIL_ASPECT_RATIO = 16 / 9;
const THUMBNAIL_ASPECT_RATIO_RECIPROCAL = 9 / 16;
const CROP_BOX_WIDTH = 202;
const CROP_BOX_HEIGHT = 114;

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

  init() {
    this._super(...arguments);
    this.set('thumbnailNotSelected', true);
  },

  didInsertElement() {
    this.$().parents('form').twitchFileUpload({
      dataType: 'json',
      singleFileUploads: false,
      replaceFileInput: true,
      formData: () => {
        return [
          { name: 'crop_x', value: this.crop_x },
          { name: 'crop_y', value: this.crop_y },
          { name: 'crop_h', value: this.crop_h },
          { name: 'crop_w', value: this.crop_w }
        ];
      },
      add: (e, data) => {
        // For some reason, pasting certain strings into input boxes triggers function.
        // Return early to avoid this.
        if (data.files.length === 0) { return; }

        this.setupCropTool(data);
      }
    });
  },

  setupCropTool(data) {
    let file = data.files[0];

    let onImageLoad = (img) => {
      this.set('content.file', file);
      this.set('content.imageData', data);

      // TODO: refactor the underlying template logic here so these $ selectors
      // no longer need to reach outside of this component
      let imageContainer = $('.modal__thumbnail--main');
      let toolContainer = $('<div></div>').addClass('modal__cropper');
      let cropNode = toolContainer.append(img);
      imageContainer.append(cropNode);

      $(img).Jcrop({
        aspectRatio: THUMBNAIL_ASPECT_RATIO,
        setSelect: [0, 0, img.width, Math.ceil(img.width * THUMBNAIL_ASPECT_RATIO_RECIPROCAL)], // Default selected rectangle
        onSelect: (coords) => { this.saveCoords(coords); },
        onChange: (coords) => { this.saveCoords(coords); },
        boxWidth: CROP_BOX_WIDTH,
        boxHeight: CROP_BOX_HEIGHT
      });
    };

    loadImage(file, onImageLoad, { canvas: true });
  },

  saveCoords(coords) {
    this.crop_x = Math.ceil(coords.x);
    this.crop_y = Math.ceil(coords.y);
    this.crop_h = Math.ceil(coords.h);
    this.crop_w = Math.ceil(coords.w);
  }
});
