'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 _handlebars = require('handlebars');

var _handlebars2 = _interopRequireDefault(_handlebars);

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 EditorFiles = function () {
  function EditorFiles() {
    var _this = this;

    _classCallCheck(this, EditorFiles);

    this._ajax = _nanoajax2.default.ajax;
    this.referenceTabButton = document.querySelector('[data-manager-show="references-files"]');
    if (this.referenceTabButton != null) {
      this.referenceTabButton.addEventListener('click', function () {
        _this._ajax({
          url: '/abe/reference/',
          body: '',
          cors: true,
          method: 'get'
        }, function (code, responseText) {
          var resp = JSON.parse(responseText);
          var referenceListHtml = document.querySelector('.references-files-wrapper');
          var template = _handlebars2.default.compile(referenceListHtml.innerHTML);
          var compiled = template(resp);
          referenceListHtml.innerHTML = compiled;
          _this.referenceLinks = document.querySelectorAll('[data-ref-json]');
          _this.textArea = document.querySelector('.display-json');
          _this.jsonError = document.querySelector('.json-error');
          if (!_this.referenceLinks) return;
          _this.rebind();
        });
      });
    }
  }

  _createClass(EditorFiles, [{
    key: 'rebind',
    value: function rebind() {
      var _this2 = this;

      Array.prototype.forEach.call(this.referenceLinks, function (referenceLink) {
        referenceLink.addEventListener('click', function (e) {
          e.preventDefault();
          _this2.textArea.style.opacity = 1;
          Array.prototype.forEach.call(_this2.referenceLinks, function (referenceLink) {
            _this2.textArea.classList.remove('error');
            _this2.jsonError.style.opacity = 0;
            referenceLink.classList.remove('active');
          });
          e.target.classList.add('active');
          if (parseInt(e.target.getAttribute('data-error')) === 1) {
            _this2.textArea.classList.add('error');
            _this2.jsonError.style.opacity = 1;
          }
          _this2.displayReference(e.target);
        });
      });
      this.textArea.addEventListener('blur', function () {
        _this2.save();
      });
    }
  }, {
    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 EditorFiles;
}();

exports.default = EditorFiles;