'use strict';

var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];

function toPojo(obj) {
  return JSON.parse(JSON.stringify(obj));
}

function replacer(match, group) {
  return new Array(group.length + 1).join('X');
}

function apply(obj, key, action) {
  for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
      var val = obj[k];
      if (k === key) {
        if (action === 'remove') {
          delete obj[k];
        } else if (action === 'censor' && typeof val === 'object') {
          delete obj[key];
        } else if (action === 'censor') {
          obj[k] = ('' + val).replace(/./g, 'X');
        } else if (/\/.+\//.test(action)) {
          var matches = action.match(/\/(.+)\//);
          if (matches) {
            var regex = new RegExp(matches[1]);
            obj[k] = ('' + val).replace(regex, replacer);
          }
        }
      } else if (typeof val === 'object') {
        val = apply(val, key, action);
      }
    }
  }
  return obj;
}

module.exports = function (obj, actionsByKey) {
  return _Object$keys(actionsByKey).reduce(function (output, key) {
    return apply(output, key, actionsByKey[key]);
  }, toPojo(obj));
};
