/* globals loadImage */
import Component from 'ember-component';
import $ from 'jquery';
import { bind } from 'ember-runloop';

const THUMBNAIL_ASPECT_RATIO = 16 / 9;
const THUMBNAIL_ASPECT_RATIO_RECIPROCAL = 9 / 16;

export default Component.extend({
  init(){
    this._super(...arguments);
    this._lastImageFile = null;
  },

  didInsertElement() {
    let imageFile = this.get('imageToCrop');

    if (imageFile === this._lastImageFile) {
      return;
    }

    let canvasTarget = this.$('.js-canvas-target');

    if (!imageFile) {
      canvasTarget.empty();
      return;
    }

    let onImageLoad = (canvas) => {
      canvasTarget.append(canvas);

      $(canvas).Jcrop({
        aspectRatio: THUMBNAIL_ASPECT_RATIO,
        setSelect: [0, 0, canvas.width, Math.ceil(canvas.width * THUMBNAIL_ASPECT_RATIO_RECIPROCAL)], // Default selected rectangle
        onSelect: bind(this, 'sendCoords'),
        onChange: bind(this, 'sendCoords'),
        boxWidth: 202,
        boxHeight: 114
      });
    };

    loadImage(imageFile, onImageLoad, { canvas: true });
    this._lastImageFile = imageFile;
  },

  sendCoords(coords) {
    this.get('onCropCoordinatesChange')({
      crop_x: Math.ceil(coords.x),
      crop_y: Math.ceil(coords.y),
      crop_h: Math.ceil(coords.h),
      crop_w: Math.ceil(coords.w)
    });
  }
});
