'use strict';

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

var _bluebird = require('bluebird');

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _cli = require('../../cli');

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

function add(obj, json, text, util) {
  var value = obj.value;

  if (obj.key.indexOf('[') > -1) {
    var key = obj.key.split('[')[0];
    var index = obj.key.match(/[^\[]+?(?=\])/)[0];
    var prop = obj.key.replace(/[^\.]+?\./, '');
    key = getDataIdWithNoSlash(key);

    try {
      obj.value = eval('json[key][index].' + prop);
    } catch (e) {

      try {
        eval('json[key][index].' + prop + ' = ' + JSON.stringify(value));
      } catch (e) {
        // no value found inside json OKEY
      }
    }
  } else {
    try {
      obj.value = eval('json.' + getDataIdWithNoSlash(obj.key));
    } catch (e) {
      // no value found inside json OKEY
    }
  }

  obj.key = getDataIdWithNoSlash(obj.key);
  if (json != null && json.abe_meta != null) {
    obj.status = json.abe_meta.status;
  }

  util.add(obj);

  return value;
}

function getDataIdWithNoSlash(key) {
  var trueKey = key;
  if (trueKey.indexOf('/') > -1) {
    trueKey = trueKey.split('/');
    trueKey = trueKey[trueKey.length - 1];
  }
  return trueKey;
}

function addToForm(match, text, json, util, arrayBlock) {
  var keyArray = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
  var i = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;

  var v = '{{' + match + '}}',
      obj = _cli.cmsData.attributes.getAll(v, json);

  var realKey;

  if (typeof keyArray !== 'undefined' && keyArray !== null) {
    realKey = obj.key.replace(/[^\.]+?\./, '');

    if (obj.key.indexOf(keyArray + '.') >= 0 && realKey.length > 0) {
      obj.keyArray = keyArray;
      obj.realKey = realKey;
      obj.key = keyArray + '[' + i + '].' + realKey;
      obj.desc = obj.desc + ' ' + i, insertAbeEach(obj, text, json, util, arrayBlock);
    } else if (util.dontHaveKey(obj.key)) {
      obj.value = json[getDataIdWithNoSlash(obj.key)];
      json[getDataIdWithNoSlash(obj.key)] = add(obj, json, text, util);
    }
  } else if (util.dontHaveKey(obj.key) && _cli.cmsData.regex.isSingleAbe(v, text)) {
    realKey = obj.key; //.replace(/\./g, '-')
    try {
      obj.value = eval('json.' + getDataIdWithNoSlash(realKey));
    } catch (e) {
      obj.value = null;
    }
    // json[getDataIdWithNoSlash(obj.key)] = 
    add(obj, json, text, util);
  }
}

function matchAttrAbe(text, json, util, arrayBlock) {
  var patt = /abe [^{{}}]+?(?=\}})/g,
      match;
  // While regexp match HandlebarsJS template item => keepgoing
  while (match = patt.exec(text)) {
    addToForm(match[0], text, json, util, arrayBlock, null, null);
  }
}

function insertAbeEach(obj, text, json, util, arrayBlock) {
  if (typeof arrayBlock[obj.keyArray][obj.realKey] === 'undefined' || arrayBlock[obj.keyArray][obj.realKey] === null) {
    arrayBlock[obj.keyArray][obj.realKey] = [];
  }
  var exist = false;
  Array.prototype.forEach.call(arrayBlock[obj.keyArray][obj.realKey], function (block) {
    if (block.key === obj.key) {
      exist = true;
    }
  });
  if (!exist) {
    arrayBlock[obj.keyArray][obj.realKey].push(obj);
  }
}

function each(text, json, util, arrayBlock) {
  var pattEach = /(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g;
  var patt = /{{(abe .*?["']) ?}}/g;
  var textEach, match;

  while (textEach = pattEach.exec(text)) {
    var i;
    var keyArray = textEach[0].match(/#each (\n|.)*?\}/);
    keyArray = keyArray[0].slice(6, keyArray[0].length - 1);

    if (keyArray.split(' ').length > 1) {
      keyArray = keyArray.split(' ')[0];
    }
    arrayBlock[keyArray] = [];
    // ce while boucle sur les block de contenu {{abe}}
    while (match = patt.exec(textEach[0])) {
      var v = match[0];

      if (v.indexOf('abe') > -1) {
        if (json[keyArray]) {
          for (i = 0; i < json[keyArray].length; i++) {
            addToForm(v, text, json, util, arrayBlock, keyArray, i);
          }
        } else {
          addToForm(v, text, json, util, arrayBlock, keyArray, 0);
        }
      }
    }

    // ici on boucle a nouveau sur les champs pour les placer a la suite dans le formulaire
    var attrArray = [],
        length = 0;
    for (var index in arrayBlock[keyArray]) {
      attrArray.push(index);
      length = arrayBlock[keyArray][index].length;
    }

    for (i = 0; i < length; i++) {
      for (var j = 0; j < attrArray.length; j++) {
        add(arrayBlock[keyArray][attrArray[j]][i], json, text, util);
      }
    }
  }
}

function addSource(text, json, util) {
  // removing each blocks potentially containing abe data type
  var pattEach = /(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g;
  text = text.replace(pattEach, '');

  var listReg = /({{abe.*type=[\'|\"]data.*}})/g;
  var match;

  while (match = listReg.exec(text)) {
    var obj = _cli.cmsData.attributes.getAll(match[0], json);

    if (obj.editable) {
      obj.value = json[getDataIdWithNoSlash(obj.key)];
      add(obj, json, text, util);
    } else {
      json[getDataIdWithNoSlash(obj.key)] = obj.source;
    }
  }
}

function orderByTabindex(a, b) {
  if (a.order < b.order) {
    return -1;
  } else if (a.order > b.order) {
    return 1;
  }

  return 0;
}

function orderBlock(util) {

  var formBlock = {};

  for (var tab in util.form) {

    var formBlockTab = {};
    for (var i = 0; i < util.form[tab].item.length; i++) {
      var blockName = util.form[tab].item[i].block === '' ? 'default_' + i : util.form[tab].item[i].block;
      if (util.form[tab].item[i].key.indexOf('[') > -1) {
        blockName = util.form[tab].item[i].key.split('[')[0];
      }
      if (typeof formBlockTab[blockName] === 'undefined' || formBlockTab[blockName] === null) {
        formBlockTab[blockName] = [];
      }
      formBlockTab[blockName].push(util.form[tab].item[i]);
    }
    if (typeof blockName !== 'undefined' && blockName !== null) {
      formBlockTab[blockName].sort(orderByTabindex);
    }
    if (typeof formBlock[tab] === 'undefined' || formBlock[tab] === null) {
      formBlock[tab] = {};
    }

    var formBlockOrdered = {};
    var arKeys = Object.keys(formBlockTab).sort(function (a, b) {
      if (parseFloat(formBlockTab[a][0].order) < parseFloat(formBlockTab[b][0].order)) {
        return -1;
      } else if (parseFloat(formBlockTab[a][0].order) > parseFloat(formBlockTab[b][0].order)) {
        return 1;
      }
      return 0;
    });

    Array.prototype.forEach.call(arKeys, function (arKey) {
      formBlockOrdered[arKey] = formBlockTab[arKey];
    });
    formBlock[tab] = formBlockOrdered;
  }

  var formTabsOrdered = {};
  var arKeysTabs = Object.keys(formBlock).sort(function (a, b) {
    if (parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) < parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
      return -1;
    } else if (parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) > parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
      return 1;
    }
    return 0;
  });

  Array.prototype.forEach.call(arKeysTabs, function (arKeysTab) {
    if (arKeysTab !== 'slug') formTabsOrdered[arKeysTab] = formBlock[arKeysTab];
  });

  formTabsOrdered['slug'] = formBlock['slug'];

  return formTabsOrdered;
}

function editor(text, json, documentLink) {
  var precontrib = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

  var p = new _bluebird.Promise(function (resolve) {
    var util = new _cli.cmsEditor.form();
    var arrayBlock = [];

    _cli.cmsData.source.getDataList(_path2.default.dirname(documentLink), text, json).then(function () {
      addSource(text, json, util);

      if (!precontrib) {
        text = _cli.cmsTemplates.template.setAbeSlugDefaultValueIfDoesntExist(text);
        text = _cli.cmsTemplates.template.setAbePrecontribDefaultValueIfDoesntExist(text);
      }

      matchAttrAbe(text, json, util, arrayBlock);
      arrayBlock = [];
      each(text, json, util, arrayBlock);

      text = _cli.cmsData.source.removeDataList(text);
      if (typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
        var links = json.abe_meta.link.split('/');
        var link = links.pop();
        json.abe_meta.cleanName = link.replace(/\..+$/, '');
        json.abe_meta.cleanFilename = links.join('/').replace(/\..+$/, '');
      }

      if (!precontrib) {
        // HOOKS beforeEditorFormBlocks
        json = _cli.abeExtend.hooks.instance.trigger('beforeEditorFormBlocks', json, text);
      }

      var blocks = orderBlock(util);

      if (!precontrib) {
        // HOOKS afterEditorFormBlocks
        blocks = _cli.abeExtend.hooks.instance.trigger('afterEditorFormBlocks', blocks, json, text);
      }

      _cli.abeEngine.instance.content = json;
      resolve({
        text: text,
        form: blocks,
        json: json
      });
    }).catch(function (e) {
      console.error(e);
    });
  });

  return p;
}