/* globals Twitch */
import Mixin from 'ember-metal/mixin';
import $ from 'jquery';

export default Mixin.create({
  didInsertElement() {
    this._super(...arguments);

    this.$().twitchFileUpload({
      singleFileUploads: false,
      dataType: 'json',
      fileInput: null,
      formData: function (form) {
        return [
          {
            name: 'regex',
            value: $(form).find('.js-code-input').val()
          }
        ];
      }
    });
  },

  change(e) {
    if (e.target.files) {
      this._validateImageDimensions(e.target);
    }
  },

  // Validate dimensions with a test image (http://stackoverflow.com/a/8904008/955404)
  _validateImageDimensions(image) {
    let file = image.files[0];
    let img = new Image();
    let _URL = window.URL || window.webkitURL;

    let resetFormInput = function (input) {
      $(input).wrap('<form>').closest('form').get(0).reset();
      $(input).unwrap();
    };

    this.addEventListener(img, 'load', (e) => {
      let dimensionsString = image.name;
      let expectedWidth = parseInt(dimensionsString.split('x')[0], 10);
      let expectedHeight = parseInt(dimensionsString.split('x')[1], 10);
      if (e.target.width !== expectedWidth || e.target.height !== expectedHeight) {
        Twitch.notify.error(`Your image must have the dimensions ${dimensionsString}`);
        resetFormInput(image);
      }
    });

    img.src = _URL.createObjectURL(file);
  }
});
