"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 Promise = require("ipromise");

var Handler = function () {
  function Handler(handler, router) {
    (0, _classCallCheck3.default)(this, Handler);

    this.handler = handler;
    this.router = router;
  }

  (0, _createClass3.default)(Handler, [{
    key: "at",
    value: function at(fromString) {
      this.fromString = fromString;
      return this;
    }
  }, {
    key: "when",
    value: function when(condition) {
      if (typeof condition === "string") {
        this.condition = new Function("message", "with(message) {return " + condition + ";}");
      } else if (typeof condition === "function") {
        this.condition = condition;
      }
      return this;
    }
  }, {
    key: "test",
    value: function test(message) {
      return message.match(this.fromString) && (!this.condition || this.condition(message));
    }
  }, {
    key: "run",
    value: function run(message) {
      if (this.test(message)) {
        return this.handler.call(this.router, message);
      }
    }
  }]);
  return Handler;
}();

function _run(handlerList, message) {
  var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

  var promise = new Promise();
  var handler = handlerList[i];
  if (handler) {
    var ret = handler.run(message);
    if (ret && typeof ret.then === "function") {
      if (i + 1 < handlerList.length) {
        ret.then(function (data) {
          if (data === false) {
            promise.resolve(false);
          } else {
            promise.resolve(_run(handlerList, data || message, i + 1));
          }
        });
      } else {
        return ret;
      }
    } else if (ret === false) {
      promise.resolve(ret);
    } else {
      if (i + 1 < handlerList.length) {
        promise.resolve(_run(handlerList, ret || message, i + 1));
      } else {
        promise.resolve(ret);
      }
    }
  } else {
    promise.resolve();
  }
  return promise;
}
Handler.run = _run;
module.exports = Handler;