'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ExecutorLaunchDarkly = 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 _launchdarklyNodeutils = require('launchdarkly-nodeutils');

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": "LaunchDarkly",
        "context": "Set FeatureFlags",
        "options": {
          "project": "myProject",
          "environment": "dev",
          "flags": {
            "testFlagOne": true,
            "testFlagTwo": false
          }
        }
      }
 */

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

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

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

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

    (0, _createClass3.default)(ExecutorLaunchDarkly, [{
        key: 'getLDUtils',
        value: function () {
            var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
                var log, that;
                return _regenerator2.default.wrap(function _callee$(_context) {
                    while (1) {
                        switch (_context.prev = _context.next) {
                            case 0:
                                log = this.log;

                                if (this.ldUtils) {
                                    _context.next = 6;
                                    break;
                                }

                                that = this;
                                return _context.abrupt('return', new _launchdarklyNodeutils.LaunchDarklyUtils().create(process.env.LAUNCHDARKLY_API_TOKEN, log).then(function (handle) {
                                    that.ldUtils = handle;
                                    return _promise2.default.resolve(handle);
                                }));

                            case 6:
                                return _context.abrupt('return', _promise2.default.resolve(this.ldUtils));

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

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

            return getLDUtils;
        }()
    }, {
        key: 'getFlagValue',
        value: function () {
            var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(task, flagName) {
                var log;
                return _regenerator2.default.wrap(function _callee2$(_context2) {
                    while (1) {
                        switch (_context2.prev = _context2.next) {
                            case 0:
                                log = this.log;

                                log.info('Getting Flag Value for Flag \'' + flagName + '\'');
                                return _context2.abrupt('return', this.getLDUtils().then(function (ldUtils) {
                                    return ldUtils.flags.getFeatureFlagState(task.options.project, flagName, task.options.environment);
                                }));

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

            function getFlagValue(_x, _x2) {
                return _ref2.apply(this, arguments);
            }

            return getFlagValue;
        }()
    }, {
        key: 'setFlagValue',
        value: function () {
            var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(task, flagName, flagValue) {
                var _this2 = this;

                var log, oldFlagValue, changed;
                return _regenerator2.default.wrap(function _callee4$(_context4) {
                    while (1) {
                        switch (_context4.prev = _context4.next) {
                            case 0:
                                log = this.log;

                                log.info('Setting Flag \'' + flagName + '\' to \'' + flagValue + '\'');
                                _context4.next = 4;
                                return this.getFlagValue(task, flagName);

                            case 4:
                                oldFlagValue = _context4.sent;
                                changed = false;

                                if (!(oldFlagValue !== flagValue)) {
                                    _context4.next = 13;
                                    break;
                                }

                                // Values are Different, Update Flag Value Using API
                                log.info('Updating Flag Value for \'' + flagName + '\'');
                                _context4.next = 10;
                                return this.getLDUtils().then(function () {
                                    var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(ldUtils) {
                                        return _regenerator2.default.wrap(function _callee3$(_context3) {
                                            while (1) {
                                                switch (_context3.prev = _context3.next) {
                                                    case 0:
                                                        _context3.next = 2;
                                                        return ldUtils.flags.toggleFeatureFlag(task.options.project, flagName, task.options.environment, flagValue);

                                                    case 2:
                                                    case 'end':
                                                        return _context3.stop();
                                                }
                                            }
                                        }, _callee3, _this2);
                                    }));

                                    return function (_x6) {
                                        return _ref4.apply(this, arguments);
                                    };
                                }());

                            case 10:
                                changed = true;
                                _context4.next = 14;
                                break;

                            case 13:
                                // Values are the Same, no Update Needed
                                log.info('Skipping Update for Flag \'' + flagName + '\'');

                            case 14:
                                return _context4.abrupt('return', {
                                    flagName: flagName,
                                    newValue: flagValue,
                                    oldValue: oldFlagValue,
                                    changed: changed
                                });

                            case 15:
                            case 'end':
                                return _context4.stop();
                        }
                    }
                }, _callee4, this);
            }));

            function setFlagValue(_x3, _x4, _x5) {
                return _ref3.apply(this, arguments);
            }

            return setFlagValue;
        }()
    }, {
        key: 'executeTask',
        value: function () {
            var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(task) {
                var log, flags, results, changedCount, details, flagName, result, _resultSummary, resultSummary;

                return _regenerator2.default.wrap(function _callee5$(_context5) {
                    while (1) {
                        switch (_context5.prev = _context5.next) {
                            case 0:
                                log = this.log;
                                flags = task.options.flags;
                                results = [];
                                changedCount = 0;
                                details = '';


                                log.info('Starting LaunchDarkly api calls. Flags: ' + _formatJson2.default.plain(flags));
                                _context5.prev = 6;
                                _context5.t0 = _regenerator2.default.keys(flags);

                            case 8:
                                if ((_context5.t1 = _context5.t0()).done) {
                                    _context5.next = 17;
                                    break;
                                }

                                flagName = _context5.t1.value;
                                _context5.next = 12;
                                return this.setFlagValue(task, flagName, flags[flagName]);

                            case 12:
                                result = _context5.sent;

                                results.push(result);

                                if (result.changed) {
                                    details += flagName + ' = ' + result.newValue + ' (was ' + result.oldValue + ')<br>';
                                    changedCount++;
                                } else {
                                    details += flagName + ' = ' + result.newValue + ' (no change)<br>';
                                }
                                _context5.next = 8;
                                break;

                            case 17:
                                _context5.next = 24;
                                break;

                            case 19:
                                _context5.prev = 19;
                                _context5.t2 = _context5['catch'](6);
                                _resultSummary = {
                                    passed: false,
                                    url: 'https://github.com',
                                    message: 'failed to set flags',
                                    details: _context5.t2.message
                                };


                                task.results = _resultSummary;
                                return _context5.abrupt('return', _promise2.default.reject(task));

                            case 24:
                                resultSummary = {
                                    passed: true,
                                    url: 'https://github.com',
                                    message: 'Updated ' + changedCount + ' Flags',
                                    details: details
                                };


                                task.results = resultSummary;

                                return _context5.abrupt('return', _promise2.default.resolve(task));

                            case 27:
                            case 'end':
                                return _context5.stop();
                        }
                    }
                }, _callee5, this, [[6, 19]]);
            }));

            function executeTask(_x7) {
                return _ref5.apply(this, arguments);
            }

            return executeTask;
        }()
    }]);
    return ExecutorLaunchDarkly;
}(_Executor2.Executor);

_Executor2.Executor.register('LaunchDarkly', ExecutorLaunchDarkly);