'use strict';

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

var _handlebars = require('handlebars');

var _handlebars2 = _interopRequireDefault(_handlebars);

var _abeEngine = require('./abeEngine');

var _abeEngine2 = _interopRequireDefault(_abeEngine);

var _xss = require('xss');

var _xss2 = _interopRequireDefault(_xss);

var _ = require('../../../');

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

/**
 * Abe handlebar helper, that retrieve text to add to handlebars templating engine
 * @return {String} the string to replace {{ handlebars_key }}
 */
function compileAbe() {
  var content = _abeEngine2.default.instance.content;
  if (arguments[0].hash['key'] == null) return '';
  var key;
  var hash;
  var value;
  var testXSS;

  if (arguments[0].hash['key'].indexOf('}-') > 0) {
    key = arguments[0].hash['key'].split('-');
    key = key[key.length - 1];
    hash = arguments[0].hash;
    // hash.key = hash.key.replace(/\{\{@index\}\}/, '[{{@index}}]')
    hash.key = hash.key.replace(/\{\{@index\}\}/, '[' + arguments[0].data.index + ']');
    try {
      value = content ? eval('content.' + hash.dictionnary + '[' + arguments[0].data.index + '].' + key) : hash.key;
      // value = content ? content[hash['dictionnary']][arguments[0].data.index][key] : hash.key
    } catch (e) {
      console.log(e.stack);
      value = '';
    }
    if (typeof value === 'function' || value == null) {
      value = '';
    }
    if (hash.type != null && hash.type === 'rich') {
      testXSS = (0, _xss2.default)(value.replace(/&quot;/g, '"'), {
        'whiteList': _.config.htmlWhiteList,
        stripIgnoreTag: true
      });
      return new _handlebars2.default.SafeString(testXSS);
    }
    return value.replace(/%27/, '\'');
  }

  key = arguments[0].hash['key'].replace('.', '-');

  hash = arguments[0].hash;
  if (content) {
    try {
      value = eval('content.' + hash.key);
    } catch (e) {
      value = hash.key;
    }
  } else {
    value = hash.key;
  }
  // value = ((content) ? content[hash.key.replace('.', '-')] : hash.key)
  if (typeof value === 'function' || value == null) {
    value = '';
  }

  if (hash.type != null && hash.type === 'rich') {
    testXSS = (0, _xss2.default)(value.replace(/&quot;/g, '"'), {
      'whiteList': _.config.htmlWhiteList,
      stripIgnoreTag: true
    });
    return new _handlebars2.default.SafeString(testXSS);
  }
  return value.replace(/%27/, '\'');
}