'use strict';

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

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _promise = require('babel-runtime/core-js/promise');

var _promise2 = _interopRequireDefault(_promise);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

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

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

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

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

require('source-map-support/register');

var _Executor2 = require('../agent/Executor');

var _requestPromiseNative = require('request-promise-native');

var _requestPromiseNative2 = _interopRequireDefault(_requestPromiseNative);

var _formatJson = require('format-json');

var _formatJson2 = _interopRequireDefault(_formatJson);

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

/**
 * Sample .githubTaskManager.json task config
 *
 * see: https://github.com/zotoio/github-task-manager/wiki/Structure-of-.githubTaskManager.json
 *
 * {
        "executor": "Http",
        "context": "avtest",
        "options": {
          "har": {
            "url": "https://httpbin.org/headers",
            "method": "GET",
            "headers": [
              {
                "name": "accept",
                "value": "application/json"
              }
            ]
          },
          "validator": {
            "type": "bodyJson",
            "objectCheckRef": "headers.Host",
            "objectCheckVal": "httpbin.org"
          }
        }
      }
 */

var ExecutorHttp = exports.ExecutorHttp = function (_Executor) {
    (0, _inherits3.default)(ExecutorHttp, _Executor);

    function ExecutorHttp(eventData, log) {
        (0, _classCallCheck3.default)(this, ExecutorHttp);

        var _this = (0, _possibleConstructorReturn3.default)(this, (ExecutorHttp.__proto__ || (0, _getPrototypeOf2.default)(ExecutorHttp)).call(this, eventData, log));

        _this.log = log;
        _this.options = _this.getOptions();
        return _this;
    }

    (0, _createClass3.default)(ExecutorHttp, [{
        key: 'executeTask',
        value: function () {
            var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(task) {
                var _this2 = this;

                var log, har;
                return _regenerator2.default.wrap(function _callee$(_context) {
                    while (1) {
                        switch (_context.prev = _context.next) {
                            case 0:
                                log = this.log;
                                har = task.options.har;


                                log.info('Starting http request..');

                                return _context.abrupt('return', (0, _requestPromiseNative2.default)({
                                    proxy: task.options.proxy || this.options.proxy || null,
                                    resolveWithFullResponse: true,
                                    har: har
                                }).then(function (response) {
                                    var res = _formatJson2.default.plain(response);
                                    log.info(res);
                                    if (_this2.validate(task, response)) {
                                        task.results = {
                                            passed: true,
                                            message: 'Request completed',
                                            url: 'http://www.softwareishard.com/blog/har-12-spec/#request',
                                            details: '\n\n**response:**\n\n```\n\n' + res + '\n```\n\n'
                                        };
                                        return _promise2.default.resolve(task);
                                    } else {
                                        task.results = {
                                            passed: false,
                                            message: 'Response validation failed',
                                            url: 'http://www.softwareishard.com/blog/har-12-spec/#request',
                                            details: '\n\n**response:**\n\n```\n\n' + res + '\n```\n\n'
                                        };
                                        return _promise2.default.reject(task);
                                    }
                                }).catch(function (e) {
                                    log.error(e.message);
                                    task.results = {
                                        passed: false,
                                        message: 'an unhandled http error occurred',
                                        details: e.message,
                                        url: 'http://www.softwareishard.com/blog/har-12-spec/#request'
                                    };
                                    return _promise2.default.reject(task);
                                }));

                            case 4:
                            case 'end':
                                return _context.stop();
                        }
                    }
                }, _callee, this);
            }));

            function executeTask(_x) {
                return _ref.apply(this, arguments);
            }

            return executeTask;
        }()
    }, {
        key: 'validate',
        value: function validate(task, response) {
            var log = this.log;
            var valid = true;

            if (task.options.validator && task.options.validator.type === 'bodyJson') {
                log.info('validating response: bodyJson');

                try {
                    var bodyObj = JSON.parse(response.body);

                    var objectCheckRef = task.options.validator.objectCheckRef;
                    var objectCheckVal = task.options.validator.objectCheckVal;

                    log.info('checking ' + objectCheckRef + ' === ' + objectCheckVal);

                    valid = objectCheckRef.split('.').reduce(function (o, i) {
                        return o[i];
                    }, bodyObj) === objectCheckVal;
                } catch (e) {
                    log.error('http bodyJson validation failed', e);
                    valid = false;
                }
            }

            return valid;
        }
    }]);
    return ExecutorHttp;
}(_Executor2.Executor);

_Executor2.Executor.register('Http', ExecutorHttp);