'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _on = require('on');

var _on2 = _interopRequireDefault(_on);

var _popup = require('./popup');

var _popup2 = _interopRequireDefault(_popup);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// allow override from plugins
window.ImagePickerUpload = {
  getPopup: function getPopup() {

    return '<div class="form-group" >\n              <div class="input-group img-upload">\n                <div class="input-group-addon image">\n                  <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>\n                </div>\n                <input type="text" id="wysiwyg-image-text" name="wysiwyg-image-text" placeholder="image or video (.mp4)" value="" class="form-control form-abe file-input">\n                <div class="upload-wrapper">\n                  <input class="form-control" id="wysiwyg-image-upload" name="wysiwyg-image-upload" value="" type="file" title="upload an image">\n                  <span class="percent">\n                    <span class="glyphicon glyphicon-upload" aria-hidden="true"></span>\n                  </span>\n                </div>\n                <div class="btn-add-img-wrapper">\n                  <button class="btn-add-img btn btn-primary">add</button>\n                </div>\n              </div>\n              <div class="input-error">\n              </div>\n            </div>';
  },
  init: function init(callBack) {
    var wysiwygText = document.querySelector('#wysiwyg-image-text');
    var wysiwygUpload = document.querySelector('#wysiwyg-image-upload');
    var btnAddImg = document.querySelector('.btn-add-img');
    var uploadImage = function uploadImage(e) {
      var target = e.target;
      var formData = new FormData();
      if (target.value == '') {
        console.log('Please choose file!');
        return false;
      }
      var parentTarget = target.parentNode.parentNode;
      var percent = parentTarget.querySelector('.percent');
      var percentHtml = percent.innerHTML;
      var file = target.files[0];
      var uploadError = parentTarget.nextElementSibling;
      uploadError.classList.remove('show');
      uploadError.textContent = '';
      formData.append('uploadfile', file);
      var xhr = new XMLHttpRequest();
      xhr.open('post', '/abe/upload/?baseUrl=' + CONFIG.FILEPATH + '&input=' + target.outerHTML, true);
      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          var percentage = e.loaded / e.total * 100;
          percent.textContent = percentage.toFixed(0) + '%';
        }
      };
      xhr.onerror = function () {
        console.log('An error occurred while submitting the form. Maybe your file is too big');
      };
      xhr.onload = function () {
        var resp = JSON.parse(xhr.responseText);
        if (resp.error) {
          uploadError.textContent = resp.response;
          uploadError.classList.add('show');
          percent.innerHTML = percentHtml;
          return;
        }
        var input = parentTarget.querySelector('input.file-input');
        input.value = resp.filePath;
        input.focus();
        input.blur();
        setTimeout(function () {
          percent.innerHTML = percentHtml;
        }, 1000);
        wysiwygUpload.removeEventListener('change', uploadImage);
        btnAddImg.removeEventListener('click', addImg);
        callBack(resp.filePath);
      };
      percent.textContent = '0%';
      xhr.send(formData);
    };

    var addImg = function addImg() {
      callBack(wysiwygText.value);
    };

    wysiwygUpload.addEventListener('change', uploadImage);
    btnAddImg.addEventListener('click', addImg);

    return this;
  }
};

var ImagePicker = function () {
  function ImagePicker(wrapper) {
    _classCallCheck(this, ImagePicker);

    this.popup = new _popup2.default(wrapper);
    this.wrapper = wrapper;
    this.bindEvt();
  }

  _createClass(ImagePicker, [{
    key: 'bindEvt',
    value: function bindEvt() {
      this.onImg = (0, _on2.default)(this);
    }
  }, {
    key: 'show',
    value: function show(el) {
      var _this = this;

      this.wrapper.innerHTML = window.ImagePickerUpload.getPopup();
      var elBounds = el.getBoundingClientRect();
      this.popup.open(elBounds.left, elBounds.top + elBounds.height + 5);

      window.ImagePickerUpload.init(function (value) {
        _this.onImg._fire({ image: value });
        _this.popup.close();
      });
    }
  }]);

  return ImagePicker;
}();

exports.default = ImagePicker;