'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; }; }(); /*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 EditorStructures = function () {
  function EditorStructures() {
    _classCallCheck(this, EditorStructures);

    var struc = document.querySelector('.structure-json');
    if (!(struc != null)) return;
    this._ajax = _nanoajax2.default.ajax;
    this.datas = JSON.parse(struc.value);
    this.structureWrapper = document.querySelector('.structure-wrapper');
    this.folderName = document.querySelector('input.folder-name');

    var lvl_0 = this.createFolder('structure/', 0, '', 'structure', '');

    this.createStructure(lvl_0, this.datas);
    this.structureWrapper.appendChild(lvl_0);
    this.rebind();
  }

  _createClass(EditorStructures, [{
    key: 'createFolder',
    value: function createFolder(path, level, daddy, folderName) {
      var hidden = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'hidden';

      var folder = document.createElement('div');
      if (hidden && hidden !== '') folder.classList.add(hidden);
      folder.classList.add('structure-folder');
      folder.setAttribute('data-path', path.replace(/\/+$/, '') + '/');
      folder.setAttribute('data-level', level);
      folder.setAttribute('data-daddy', daddy);

      var span = document.createElement('span');
      var html = '<span class="glyphicon glyphicon-chevron-right arrow" aria-hidden="true"></span>\n                ' + folderName + ' \n                <div class="structure-tool">\n                  <span class="glyphicon glyphicon-plus folder-action" data-init="0" data-action="add" aria-hidden="true"></span>';
      if (level !== 0) html += '<span class="glyphicon glyphicon-minus folder-action" data-init="0" data-action="remove" aria-hidden="true"></span>';
      html += '</div>';
      span.innerHTML = html;
      folder.appendChild(span);

      this.bindArrow(span.querySelector('.arrow'));

      return folder;
    }
  }, {
    key: 'toggleFolder',
    value: function toggleFolder(daddy) {
      var forceState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

      var folders = daddy.querySelectorAll('[data-level="' + (parseInt(daddy.getAttribute('data-level')) + 1) + '"]');
      if (folders) {
        if (!daddy.classList.contains('open') || forceState === 'open') {
          daddy.classList.add('open');
          Array.prototype.forEach.call(folders, function (folder) {
            folder.classList.remove('hidden');
          });
        } else {
          daddy.classList.remove('open');
          Array.prototype.forEach.call(folders, function (folder) {
            folder.classList.add('hidden');
          });
        }
      }
    }
  }, {
    key: 'bindArrow',
    value: function bindArrow(arrow) {
      var _this = this;

      arrow.addEventListener('click', function () {
        _this.toggleFolder(arrow.parentNode.parentNode);
      });
    }
  }, {
    key: 'createStructure',
    value: function createStructure(daddy, datas) {
      var _this2 = this;

      Array.prototype.forEach.call(datas, function (data) {
        var folderName = data['path'].split('/');
        var folder = _this2.createFolder(data['path'], parseInt(daddy.getAttribute('data-level')) + 1, daddy.getAttribute('data-daddy'), folderName[folderName.length - 1]);
        daddy.appendChild(folder);

        if (data.folders && data.folders.length > 0) _this2.createStructure(folder, data.folders);
      });
    }
  }, {
    key: 'add',
    value: function add(element) {
      var _this3 = this;

      this.toggleFolder(element, 'open');
      this.folderName.removeAttribute('disabled');
      this.folderName.focus();
      this.folderName.setAttribute('data-folder', '[data-path="' + element.getAttribute('data-path') + '"]');

      var writeFolderName = function writeFolderName(e) {
        var value = _this3.folderName.value;
        if (/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(value)) _this3.folderName.classList.remove('error');else _this3.folderName.classList.add('error');
        if (e.keyCode === 13) {
          if (/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(value)) {
            _this3.folderName.removeEventListener('keyup', writeFolderName);
            _this3.folderName.setAttribute('disabled', 1);
            var newFolderDaddy = document.querySelector(_this3.folderName.getAttribute('data-folder'));
            var path = newFolderDaddy.getAttribute('data-path').split('/');
            path.pop();
            path = path.concat(value).join('/');
            var folder = _this3.createFolder(newFolderDaddy.getAttribute('data-path') + value, parseInt(newFolderDaddy.getAttribute('data-level')) + 1, newFolderDaddy.getAttribute('data-daddy'), value, '');
            newFolderDaddy.appendChild(folder);
            _this3.rebind();
            _this3.save(_qs2.default.stringify({ type: 'add', folderPath: newFolderDaddy.getAttribute('data-path') + value }));
            _this3.folderName.value = '';
          }
        }
      };

      this.folderName.removeEventListener('keyup', writeFolderName);
      this.folderName.addEventListener('keyup', writeFolderName);
    }
  }, {
    key: 'remove',
    value: function remove(element) {
      this.save(_qs2.default.stringify({ type: 'remove', folderPath: element.getAttribute('data-path') }));
      element.parentNode.removeChild(element);
    }
  }, {
    key: 'save',
    value: function save(body) {
      this._ajax({ url: '/abe/structure/', body: body, cors: true, method: 'post' }, function () {});
    }
  }, {
    key: 'rebind',
    value: function rebind() {
      var _this4 = this;

      var folderActions = document.querySelectorAll('.folder-action');
      Array.prototype.forEach.call(folderActions, function (folderAction) {
        if (parseInt(folderAction.getAttribute('data-init')) === 0) {
          folderAction.setAttribute('data-init', 1);
          folderAction.addEventListener('click', function (e) {
            var target = e.target;
            _this4[target.getAttribute('data-action')](target.parentNode.parentNode.parentNode);
          });
        }
      });
    }
  }]);

  return EditorStructures;
}();

exports.default = EditorStructures;