'use strict';

Object.defineProperty(exports, “__esModule”, {

value: true

});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (“value” in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _underscore = require('underscore');

var _underscore2 = _interopRequireDefault(_underscore);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _handler_base = require('./handler_base');

var _handler_base2 = _interopRequireDefault(_handler_base);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(“this hasn't been initialised - super() hasn't been called”); } return call && (typeof call === “object” || typeof call === “function”) ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== “function” && superClass !== null) { throw new TypeError(“Super expression must either be null or a function, not ” + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**

* Represents a proxied HTTP request for which the response is generated by custom user function.
* This is useful e.g. when providing access to external APIs via HTTP proxy interface.
*/

var HandlerCustomResponse = function (_HandlerBase) {

_inherits(HandlerCustomResponse, _HandlerBase);

function HandlerCustomResponse(options) {
    _classCallCheck(this, HandlerCustomResponse);

    var _this = _possibleConstructorReturn(this, (HandlerCustomResponse.__proto__ || Object.getPrototypeOf(HandlerCustomResponse)).call(this, options));

    _this.customResponseFunction = options.customResponseFunction;
    if (!_this.customResponseFunction) throw new Error('The "customResponseFunction" option is required');
    return _this;
}

_createClass(HandlerCustomResponse, [{
    key: 'run',
    value: function run() {
        var _this2 = this;

        var reqOpts = this.trgParsed;
        reqOpts.method = this.srcRequest.method;
        reqOpts.headers = {};

        _bluebird2.default.resolve().then(function () {
            return _this2.customResponseFunction();
        }).then(function (customResponse) {
            if (_this2.isClosed) return;

            if (!customResponse) {
                throw new Error('The user-provided "customResponseFunction" must return an object.');
            }

            var statusCode = customResponse.statusCode || 200;
            var length = customResponse.body ? customResponse.body.length : null;

            _this2.log('Received custom user response (' + statusCode + ', length: ' + length + ', encoding: ' + customResponse.encoding + ')');

            // Forward custom response to source
            _this2.srcResponse.statusCode = statusCode;

            _underscore2.default.each(customResponse.headers, function (value, key) {
                _this2.srcResponse.setHeader(key, value);
            });

            return new _bluebird2.default(function (resolve, reject) {
                _this2.srcGotResponse = true;
                _this2.srcResponse.end(customResponse.body, customResponse.encoding, function (err) {
                    if (err) return reject(err);
                    resolve();
                });
            });
        }).then(function () {
            _this2.log('Custom response sent to source');
        }).catch(function (err) {
            if (_this2.isClosed) return;
            _this2.log('Custom response function failed: ' + (err.stack || err));
            _this2.fail(err);
        });
    }
}]);

return HandlerCustomResponse;

}(_handler_base2.default);

exports.default = HandlerCustomResponse;