'use strict';

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

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

var invok = require('invok');
var Promise = require('ipromise');

var Filter = function () {
  function Filter(handler, condition) {
    (0, _classCallCheck3.default)(this, Filter);

    this.condition = condition;
    this.handler = handler;
    this.isGeneratorFunction = Object.prototype.toString.call(handler) === '[object GeneratorFunction]';
    if (typeof this.condition === 'string') {
      this.condition = new Function('message', 'with(message) {return ' + this.condition + ';}');
    }
  }

  (0, _createClass3.default)(Filter, [{
    key: 'when',
    value: function when(condition) {
      if (condition === 'string') {
        this.condition = new Function('message', 'with(message) {return ' + condition + ';}');
      }
    }
  }, {
    key: 'run',
    value: function run(message, next) {
      if (!this.condition || this.condition(message)) {
        if (this.isGeneratorFunction) {
          return invok(this.handler, this, [message, next]);
        } else {
          var p = new Promise();
          this.handler(message, function () {
            next().linkTo(p);
          });
          return p;
        }
      } else {
        return next();
      }
    }
  }]);
  return Filter;
}();

function resolveFilterChain(message, filterChain) {
  var currentIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

  return filterChain[currentIndex].run(message, function () {
    return currentIndex + 1 < filterChain.length ? resolveFilterChain(message, filterChain, currentIndex + 1) : Promise.resolve();
  });
}
Filter.resolveFilterChain = resolveFilterChain;
module.exports = Filter;