'use strict';

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, window, $, Event */

var _Devtool = require('./devtool/Devtool');

var _EditorInputs = require('./modules/EditorInputs');

var _EditorInputs2 = _interopRequireDefault(_EditorInputs);

var _EditorBlock = require('./modules/EditorBlock');

var _EditorBlock2 = _interopRequireDefault(_EditorBlock);

var _EditorFiles = require('./modules/EditorFiles');

var _EditorFiles2 = _interopRequireDefault(_EditorFiles);

var _EditorSave = require('./modules/EditorSave');

var _EditorSave2 = _interopRequireDefault(_EditorSave);

var _EditorJson = require('./modules/EditorJson');

var _EditorJson2 = _interopRequireDefault(_EditorJson);

var _EditorManager = require('./modules/EditorManager');

var _EditorManager2 = _interopRequireDefault(_EditorManager);

var _EditorAutocomplete = require('./modules/EditorAutocomplete');

var _EditorAutocomplete2 = _interopRequireDefault(_EditorAutocomplete);

var _EditorReload = require('./modules/EditorReload');

var _EditorReload2 = _interopRequireDefault(_EditorReload);

var _EditorReferences = require('./modules/EditorReferences');

var _EditorReferences2 = _interopRequireDefault(_EditorReferences);

var _EditorStructures = require('./modules/EditorStructures');

var _EditorStructures2 = _interopRequireDefault(_EditorStructures);

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 htmlTag = document.querySelector('html');
window.CONFIG = JSON.parse(htmlTag.getAttribute('data-config'));
// window.json = JSON.parse(unescape(htmlTag.getAttribute('data-json').replace(/&quot;/g, '\"')))
var j = htmlTag.getAttribute('data-json');
if (j != null) {
  j = j.replace(/&quot;/g, '"');
  j = unescape(j);
  j = j.replace(/\%27/g, '\'');
  window.json = JSON.parse(j);
} else {
  window.json = {};
}
var l = htmlTag.getAttribute('data-locales');
if (l != null) {

  window.Locales = JSON.parse(l);
} else {
  window.Locales = {};
}
var s = htmlTag.getAttribute('data-slugs');
if (s != null) {
  window.slugs = JSON.parse(s);
} else {
  window.slugs = {};
}

var Engine = function () {
  function Engine() {
    var _this = this;

    _classCallCheck(this, Engine);

    this._blocks = new _EditorBlock2.default();
    this._inputs = new _EditorInputs2.default();
    this._files = new _EditorFiles2.default();
    this._save = new _EditorSave2.default();
    this._manager = new _EditorManager2.default();
    this._autocomplete = new _EditorAutocomplete2.default();
    this._dev = new _Devtool.Devtool();
    this.reference = new _EditorReferences2.default();
    this.structure = new _EditorStructures2.default();

    this.json = _EditorJson2.default.instance;

    this._bindEvents();

    this.table = null;
    this.columns = [{
      'data': null,
      'defaultContent': '',
      'orderable': false
    }, {
      'data': 'abe_meta.link'
    }, {
      'data': 'abe_meta.template'
    }, {
      'data': null,
      'defaultContent': ''
    }];

    Array.prototype.forEach.call(workflow, function (flow) {
      _this.columns.push({ 'data': null,
        'defaultContent': '',
        'orderable': false
      });
    });

    this.columns.push({
      'data': null,
      'defaultContent': '',
      'orderable': false
    });

    $(document).ready(function () {
      _this.table = $('#navigation-list').DataTable({
        'pageLength': 50,
        'processing': true,
        'serverSide': true,
        'ajax': '/abe/paginate',
        'columns': _this.columns,
        'order': [[3, 'desc']],
        'stateSave': true,
        'drawCallback': function drawCallback(settings) {
          window.abe.manager.rebind();
        },
        stateSaveCallback: function stateSaveCallback(settings, data) {
          localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data));
        },
        stateLoadCallback: function stateLoadCallback(settings) {
          return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance));
        },
        'createdRow': function createdRow(row, data, index) {
          var actions = '<div class="row icons-action">';
          if (data.publish != null) {
            actions += '<a href="/abe/operations/unpublish' + data.abe_meta.link + '"\n                 title="Unpublish"\n                 class="icon" data-unpublish="true" data-text="Are you sure you want to unpublish : ' + data.abe_meta.link + '"\n                 title="unpublish">\n                <span class="glyphicon glyphicon-eye-close"></span>\n              </a>';
          }

          actions += '<a href="/abe/operations/delete/' + data.abe_meta.status + data.abe_meta.link + '"\n               title="Delete"\n               class="icon"\n               data-delete="true"\n               data-text="Are you sure you want to delete : ' + data.abe_meta.link + '"\n               title="remove">\n              <span class="glyphicon glyphicon-trash"></span>\n            </a></div>';

          var i = 4;
          Array.prototype.forEach.call(workflow, function (flow) {
            var wkf = '';
            if (typeof data[flow] !== 'undefined' && flow === 'publish') {
              wkf = '<a href="/abe/editor' + data[flow].html + '" class="checkmark label-published" title="' + data[flow].cleanDate + '">&#10004;</a>';
            }
            if (data.abe_meta.status == flow && flow !== 'publish') {
              wkf = '<a href="/abe/editor' + data[flow].html + '" class="label label-default label-draft" title="' + data[flow].cleanDate + '">' + flow + '</a>';
            }
            $('td', row).eq(i).html(wkf);
            ++i;
          });

          $('td', row).eq(0).html(index + 1);
          $('td', row).eq(1).html('<a href="/abe/editor' + data.abe_meta.link + '" class="file-path">' + data.abe_meta.link + '</a>');
          $('td', row).eq(3).html(moment(data.date).format('YYYY/MM/DD'));
          $('td', row).eq(i).html(actions);
        }
      });
    });

    $('#navigation-list').on('processing.dt', function (e, settings, processing) {
      $('#navigation-list_processing').css('display', processing ? 'block' : 'none').css({ top: '150px' });
    });

    $('#navigation-list').on('preXhr.dt', function (e, settings, data) {
      if (settings.jqXHR) {
        settings.jqXHR.abort();
      }
    });

    var abeReady = new Event('abeReady');
    document.dispatchEvent(abeReady);
  }

  _createClass(Engine, [{
    key: 'inject',
    value: function inject() {
      var findComments = function findComments(el) {
        var arr = [];
        for (var i = 0; i < el.childNodes.length; i++) {
          var node = el.childNodes[i];
          if (node.nodeType === 8) {
            arr.push(node);
          } else {
            arr.push.apply(arr, findComments(node));
          }
        }
        return arr;
      };

      var commentNodes = findComments(document);

      Array.prototype.forEach.call(commentNodes, function (comment) {
        if (comment.nodeValue.indexOf('[pageHTML]') > -1) {
          var base = comment.data;
          if (typeof base !== 'undefined' && base !== null) {
            base = base.replace(/\[pageHTML\]/g, '');
            base = base.replace(/<ABE!--/g, '<!--').replace(/--ABE>/g, '-->');
            _EditorReload2.default.instance.inject(base);
          }
        }
      });
    }
  }, {
    key: '_bindEvents',
    value: function _bindEvents() {
      var _this2 = this;

      this._blocks.onNewBlock(function () {
        _this2._files.rebind();
        _this2._inputs.rebind();
      });

      this._manager.remove(function (el) {
        _this2.table.ajax.reload();
      });

      this._inputs.onReload(function () {
        _this2._save.serializeForm();
        _EditorReload2.default.instance.reload();
      });

      this._autocomplete.onReload(function () {
        _EditorReload2.default.instance.reload();
      });

      this._inputs.onBlur(function () {
        _this2._save.serializeForm();
      });

      this._blocks.onRemoveBlock(function () {
        _this2._inputs.rebind();
        _this2._save.serializeForm(); ///**************************************** HOOLA
      });
    }
  }]);

  return Engine;
}();

var engine = new Engine();
window.abe = {
  save: engine._save,
  json: engine.json,
  inputs: engine._inputs,
  files: engine._files,
  manager: engine._manager,
  blocks: engine._blocks,
  autocomplete: engine._autocomplete,
  editorReload: _EditorReload2.default
};

document.addEventListener('DOMContentLoaded', function () {
  if (document.querySelector('#page-template')) engine.inject();
});