'use strict';

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

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

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; }; }(); /*global document */

var _nanoajax = require('nanoajax');

var _nanoajax2 = _interopRequireDefault(_nanoajax);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

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"); } }

var EditorReferences = function () {
  function EditorReferences() {
    _classCallCheck(this, EditorReferences);

    this._ajax = _nanoajax2.default.ajax;
    this.referenceLinks = document.querySelectorAll('[data-ref-json]');
    this.textArea = document.querySelector('.display-json');
    this.jsonError = document.querySelector('.json-error');
    this.addReference = document.querySelector('.btn-add-reference');
    this.addReferenceInput = document.querySelector('.btn-add-reference input');
    if (!this.referenceLinks || this.referenceLinks.length < 1) return;
    this.nameError = this.addReference.querySelector('.error-display');
    this.rebind();
  }

  _createClass(EditorReferences, [{
    key: 'bindReference',
    value: function bindReference(referenceLink) {
      var _this = this;

      referenceLink.setAttribute('data-init', 1);
      referenceLink.addEventListener('click', function (e) {
        e.preventDefault();
        _this.textArea.style.opacity = 1;
        Array.prototype.forEach.call(_this.referenceLinks, function (referenceLink) {
          _this.textArea.classList.remove('error');
          _this.jsonError.style.opacity = 0;
          referenceLink.classList.remove('active');
        });
        e.target.classList.add('active');
        if (parseInt(e.target.getAttribute('data-error')) === 1) {
          _this.textArea.classList.add('error');
          _this.jsonError.style.opacity = 1;
        }
        _this.displayReference(e.target);
      });
    }
  }, {
    key: 'nameAlreadyExist',
    value: function nameAlreadyExist(name) {
      var res = false;
      Array.prototype.forEach.call(this.referenceLinks, function (referenceLink) {
        if (referenceLink.getAttribute('data-href') == name) res = true;
      });
      return res;
    }
  }, {
    key: 'addError',
    value: function addError(val) {
      var fullTest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

      var message = '';
      if (val.trim() === '') {
        message = 'filename is empty';
      } else if (!/^[A-Za-z0-9-\.]+(?:-[A-Za-z0-9-\.]+)*$/.test(val)) {
        message = 'filename must not contains special characteres';
      } else if (val.indexOf('.json') < 0 && fullTest) {
        message = 'missing .json extension';
      } else if (this.nameAlreadyExist(val)) {
        message = 'json reference with this name already exist';
      }
      this.nameError.textContent = message;
    }
  }, {
    key: 'rebind',
    value: function rebind() {
      var _this2 = this;

      Array.prototype.forEach.call(this.referenceLinks, function (referenceLink) {
        if (parseInt(referenceLink.getAttribute('data-init')) !== 0) return;
        _this2.bindReference(referenceLink);
      });
      this.textArea.addEventListener('blur', function () {
        _this2.save();
      });
      this.addReference.querySelector('span').addEventListener('click', function () {
        _this2.add();
      });
      this.addReferenceInput.addEventListener('keyup', function () {
        var val = _this2.addReferenceInput.value;
        if (!/^[A-Za-z0-9-\.]+(?:-[A-Za-z0-9-\.]+)*$/.test(val) || _this2.nameAlreadyExist(val)) _this2.addReference.classList.add('error');else _this2.addReference.classList.remove('error');
        _this2.addError(val, false);
      });
    }
  }, {
    key: 'add',
    value: function add() {
      var val = this.addReferenceInput.value;
      if (val.trim() !== '' && /^[A-Za-z0-9-\.]+(?:-[A-Za-z0-9-\.]+)*$/.test(val) && val.indexOf('.json') > -1 && !this.nameAlreadyExist(val)) {
        this.addReference.classList.remove('error');
        var li = document.createElement('li');
        li.classList.add('list-group-item');
        li.setAttribute('data-error', '0');
        li.setAttribute('data-href', val);
        li.setAttribute('data-ref-json', '[]');
        li.textContent = val;
        this.addReference.parentNode.insertBefore(li, this.addReference);
        this.referenceLinks = document.querySelectorAll('[data-ref-json]');
        this.bindReference(li);
      } else this.addReference.classList.remove('error');
      this.addError(val);
    }
  }, {
    key: 'save',
    value: function save() {
      var _this3 = this;

      var selectedElement = document.querySelector('.references-files-wrapper .list-group-item.active');
      var isValidJson = true;
      this.textArea.classList.remove('error');
      this.jsonError.style.opacity = 0;
      try {
        _typeof(JSON.parse(this.textArea.value)); // validate json
        var data = _qs2.default.stringify({ json: this.textArea.value, url: this.textArea.getAttribute('data-file') });
        selectedElement.setAttribute('data-ref-json', this.textArea.value);
        selectedElement.setAttribute('data-error', 0);
      } catch (e) {
        this.jsonError.textContent = e;
        isValidJson = false;
        selectedElement.setAttribute('data-error', 1);
      }
      if (isValidJson) {
        this._ajax({
          url: '/abe/reference/',
          body: data,
          cors: true,
          method: 'post'
        }, function () {
          _this3.textArea.classList.add('saved');
          setTimeout(function () {
            _this3.textArea.classList.remove('saved');
          }, 400);
        });
      } else {
        this.textArea.classList.add('error');
        this.jsonError.style.opacity = 1;
      }
    }
  }, {
    key: 'displayReference',
    value: function displayReference(element) {
      this.textArea.value = JSON.stringify(JSON.parse(element.getAttribute('data-ref-json')), null, '\t');
      this.textArea.setAttribute('data-file', element.getAttribute('data-href'));
    }
  }]);

  return EditorReferences;
}();

exports.default = EditorReferences;