'use strict';

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

var _values = require('babel-runtime/core-js/object/values');

var _values2 = _interopRequireDefault(_values);

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);

var _teamcityRestApi = require('teamcity-rest-api');

var _teamcityRestApi2 = _interopRequireDefault(_teamcityRestApi);

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

var _requestPromiseNative2 = _interopRequireDefault(_requestPromiseNative);

var _jsontoxml = require('jsontoxml');

var _jsontoxml2 = _interopRequireDefault(_jsontoxml);

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

var _AgentUtils = require('../agent/AgentUtils');

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

var log = _AgentUtils.AgentUtils.logger();

/**
 * Sample .githubTaskManager.json task config
 *
 * see: https://github.com/wyvern8/github-task-manager/wiki/Structure-of-.githubTaskManager.json
 *
 * {
        "executor": "TeamCity",
        "context": "run e2e tests",
        "options": {
          "jobName": "projectName_id",
          "parameters": {
            "build_tag" : "proj_wasX",
            "ENVIRONMENT" : "env_dev",
            "cuke_env" : "env_dev|staging|prod",
            "cuke_tags" : [
              "@proj_wasX",
              "@proj_wasn"
            ]
          }
        }
    }
*/

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

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

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

        _this.options = _this.getOptions();

        _this.teamCity = _teamcityRestApi2.default.create({
            url: _this.options.GTM_TEAMCITY_URL,
            username: _this.options.GTM_TEAMCITY_USER,
            password: _this.options.GTM_TEAMCITY_PASSCODE
        });
        return _this;
    }

    (0, _createClass3.default)(ExecutorTeamCity, [{
        key: 'createTeamCityBuildNode',
        value: function createTeamCityBuildNode(task, jobName) {
            var xml = void 0;
            var xmlNode = {
                build: [{ name: 'buildType', attrs: { id: jobName } }, { name: 'properties', children: [] }]
            };

            for (var buildProperty in task.options.parameters) {
                var property = {
                    name: 'property',
                    attrs: {
                        name: buildProperty,
                        value: task.options.parameters[buildProperty]
                    }
                };
                xmlNode.build[1].children.push(property);
            }

            xml = (0, _jsontoxml2.default)(xmlNode);
            return xml;
        }
    }, {
        key: 'executeTask',
        value: function () {
            var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(task) {
                var jobName, buildNode, teamCityBuildId, completedBuild, result, overAllResult, statisticsUrl, statistics, parsedResult;
                return _regenerator2.default.wrap(function _callee$(_context) {
                    while (1) {
                        switch (_context.prev = _context.next) {
                            case 0:
                                jobName = task.options.jobName;

                                if (!(jobName == undefined)) {
                                    _context.next = 5;
                                    break;
                                }

                                _context.next = 4;
                                return _AgentUtils.AgentUtils.timeout(4000);

                            case 4:
                                return _context.abrupt('return', 'NO_MATCHING_TASK');

                            case 5:
                                buildNode = this.createTeamCityBuildNode(task, jobName);
                                _context.next = 8;
                                return this.teamCity.builds.startBuild(buildNode);

                            case 8:
                                teamCityBuildId = _context.sent;

                                log.info('TeamCity Project[' + jobName + '] with buildNumber : ' + teamCityBuildId.id + ' Started.');

                                _context.next = 12;
                                return this.waitForBuildToComplete(jobName, teamCityBuildId.id);

                            case 12:
                                completedBuild = _context.sent;

                                log.info('TeamCity Project[' + jobName + '] with buildNumber : #' + teamCityBuildId.id + ' finished with status : ' + completedBuild.status);

                                result = completedBuild.status === 'SUCCESS';
                                overAllResult = { passed: result, url: completedBuild.buildType.webUrl };

                                if (!task.options.parameters.hasOwnProperty('cuke_tags')) {
                                    _context.next = 24;
                                    break;
                                }

                                statisticsUrl = _AgentUtils.AgentUtils.formatBasicAuth(this.options.GTM_TEAMCITY_USER, this.options.GTM_TEAMCITY_PASSCODE, this.options.GTM_TEAMCITY_URL + '/app/rest/builds/id:' + teamCityBuildId.id + '/statistics');
                                _context.next = 20;
                                return this.getBuildStatistics(statisticsUrl);

                            case 20:
                                statistics = _context.sent;
                                parsedResult = this.createResultObject(statistics);

                                parsedResult.testResultsUrl = this.options.GTM_TEAMCITY_URL + '/viewLog.html?buildId=' + teamCityBuildId.id + '&tab=buildResultsDiv&buildTypeId=' + teamCityBuildId.id;

                                overAllResult.message = parsedResult;

                            case 24:

                                task.results = overAllResult;

                                return _context.abrupt('return', result ? _promise2.default.resolve(task) : _promise2.default.reject(task));

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

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

            return executeTask;
        }()
    }, {
        key: 'waitForBuildToComplete',
        value: function () {
            var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(buildName, buildNumber) {
                var buildDict, maxRetries, tries;
                return _regenerator2.default.wrap(function _callee2$(_context2) {
                    while (1) {
                        switch (_context2.prev = _context2.next) {
                            case 0:
                                _context2.next = 2;
                                return this.teamCity.builds.get(buildNumber);

                            case 2:
                                buildDict = _context2.sent;
                                maxRetries = 600;
                                tries = 1;

                            case 5:
                                if (!(buildDict.state !== 'finished' && tries++ < maxRetries)) {
                                    _context2.next = 13;
                                    break;
                                }

                                _context2.next = 8;
                                return _AgentUtils.AgentUtils.timeout(5000);

                            case 8:
                                _context2.next = 10;
                                return this.teamCity.builds.get(buildNumber).then(function (data) {
                                    log.debug('Waiting for Build \'' + buildName + '\' to Finish: ' + tries);
                                    return data;
                                });

                            case 10:
                                buildDict = _context2.sent;
                                _context2.next = 5;
                                break;

                            case 13:
                                log.debug('TeamCity Project[' + buildName + '] with buildNumber : #' + buildNumber + ' : ' + buildDict.state);
                                return _context2.abrupt('return', buildDict);

                            case 15:
                            case 'end':
                                return _context2.stop();
                        }
                    }
                }, _callee2, this);
            }));

            function waitForBuildToComplete(_x2, _x3) {
                return _ref2.apply(this, arguments);
            }

            return waitForBuildToComplete;
        }()
    }, {
        key: 'getBuildStatistics',
        value: function () {
            var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(statisticsUrl) {
                var tries, maxRetries, resultData;
                return _regenerator2.default.wrap(function _callee3$(_context3) {
                    while (1) {
                        switch (_context3.prev = _context3.next) {
                            case 0:
                                log.debug('Starting http request.. : ' + statisticsUrl);

                                tries = 1;
                                maxRetries = 100;
                                resultData = void 0;
                                _context3.next = 6;
                                return (0, _requestPromiseNative2.default)(statisticsUrl);

                            case 6:
                                resultData = _context3.sent;

                            case 7:
                                if (!(!resultData.includes('SuccessRate') && tries++ < maxRetries)) {
                                    _context3.next = 15;
                                    break;
                                }

                                _context3.next = 10;
                                return _AgentUtils.AgentUtils.timeout(3000);

                            case 10:
                                _context3.next = 12;
                                return (0, _requestPromiseNative2.default)(statisticsUrl).then(function (data) {
                                    return data;
                                });

                            case 12:
                                resultData = _context3.sent;
                                _context3.next = 7;
                                break;

                            case 15:
                                return _context3.abrupt('return', resultData);

                            case 16:
                            case 'end':
                                return _context3.stop();
                        }
                    }
                }, _callee3, this);
            }));

            function getBuildStatistics(_x4) {
                return _ref3.apply(this, arguments);
            }

            return getBuildStatistics;
        }()
    }, {
        key: 'createResultObject',
        value: function createResultObject(statistics) {
            var resultObject = {};

            var parsedJSON = _AgentUtils.AgentUtils.xmlToJson(statistics);

            var statisticsArray = (0, _values2.default)(parsedJSON.properties.property);

            var totalTestCount = _AgentUtils.AgentUtils.findMatchingElementInArray(statisticsArray, 'TotalTestCount');
            var passedTestCount = _AgentUtils.AgentUtils.findMatchingElementInArray(statisticsArray, 'PassedTestCount');
            var failedTestCount = _AgentUtils.AgentUtils.findMatchingElementInArray(statisticsArray, 'FailedTestCount');

            resultObject.TotalTestCount = totalTestCount === undefined ? 0 : totalTestCount.$.value;
            resultObject.PassedTestCount = passedTestCount === undefined ? 0 : passedTestCount.$.value;
            resultObject.FailedTestCount = failedTestCount === undefined ? 0 : failedTestCount.$.value;

            return resultObject;
        }
    }]);
    return ExecutorTeamCity;
}(_Executor2.Executor);

_Executor2.Executor.register('TeamCity', ExecutorTeamCity);