/* globals ich, loadImage */

import Component from 'ember-component';
import Ember from 'ember';
import cdnUrl from 'web-client/utilities/cdn-url';
import computed from 'ember-computed';

const { $ } = Ember;

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

  spinnerImage: computed(function () {
    return cdnUrl('images/spinner.gif');
  }),

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

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

  willDestroyElement() {
    $('body').teardownOverlay();
    this._super(...arguments);
  },

  setupCropTool: function (data) {
    let file = data.files[0];
    let self = this;
    let onImageLoad = function (img) {

      let toolContainer = $('<div></div>').addClass('js-preview card');
      let toolContent = $('<div></div>').addClass('text-content');
      let cropNode = toolContainer.append(toolContent.append(img).append(ich.crop_form_buttons()));

      $('body').overlay(cropNode, null, {width: (img.width + 90)});

      $(img).Jcrop({
        minAspectRatio: 0.5,
        setSelect: [0, 0, 320.0, 180.0], // Default selected rectangle
        onSelect: function (coords) { self.saveCoords(coords); },
        onChange: function (coords) { self.saveCoords(coords); }
      });

      $('.js-upload').on('click', function () {
        self.set('content.isUploading', true);
        data.submit()
        .done(function (response) {
          self.set('content.isUploading', false);
          self.set('content.data.image', response.image);
          self.get("imageUploaded")();
          self.set('content.isDirty', true);
        });
        $('body').trigger('overlay.hide');
      });
      $('.js-cancel-upload').on('click', function () {
        $('body').trigger('overlay.hide');
      });
    };

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

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