'use strict';

var integrationConfig = function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var _integrationPapi$rule;

        var integrationPapi;
        return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
                switch (_context.prev = _context.next) {
                    case 0:
                        if (!(Object.keys(papiOpts.behavior).length > 0 || Object.keys(papiOpts.criteria).length > 0)) {
                            _context.next = 3;
                            break;
                        }

                        console.log('returning existing config..');
                        return _context.abrupt('return', papiOpts);

                    case 3:

                        // load template papi json to inject behavior rules to test
                        integrationPapi = JSON.parse(_fs2.default.readFileSync(_appRootPath2.default + '/test/_integration.template.json', 'utf8'));

                        // add sample vars

                        (_integrationPapi$rule = integrationPapi.rules.variables).push.apply(_integrationPapi$rule, [{
                            name: 'PMUSER_TEST_MATCH',
                            value: 'exactMatchMe',
                            description: 'a test variable',
                            hidden: false,
                            sensitive: false
                        }, {
                            name: 'PMUSER_TEST_ONE_OF',
                            value: 'aklm',
                            description: 'a test variable',
                            hidden: false,
                            sensitive: false
                        }, {
                            name: 'PMUSER_TEST_BETWEEN',
                            value: '150',
                            description: 'a test variable',
                            hidden: false,
                            sensitive: false
                        }, {
                            name: 'PMUSER_TEST_SETVARIABLE',
                            value: '150',
                            description: 'placeholder',
                            hidden: false,
                            sensitive: false
                        }]);

                        _globule2.default.find(_appRootPath2.default + '/test/**/*.papi.json').forEach(function (papiPath) {

                            var isBehavior = papiPath.indexOf('behavior') > -1;

                            var papiPathParts = papiPath.split('/');
                            var papiFilename = papiPathParts[papiPathParts.length - 1];
                            var papiName = papiFilename.split('.')[0];
                            var url = papiFilename.replace('.papi.json', '');

                            var opts = JSON.parse(_fs2.default.readFileSync(papiPath, 'utf8'));

                            if (isBehavior) {
                                papiOpts.behavior[papiFilename] = opts;

                                var behaviors = [];
                                behaviors.push({
                                    name: papiName,
                                    options: opts
                                });

                                // if this is a setVariable behavior, return a header for testing result
                                if (papiName === 'setVariable') {
                                    behaviors.push({
                                        name: 'modifyOutgoingResponseHeader',
                                        options: {
                                            action: 'MODIFY',
                                            standardModifyHeaderName: 'OTHER',
                                            customHeaderName: variableCheckHeaderName,
                                            newHeaderValue: '{{user.' + opts.variableName + '}}',
                                            avoidDuplicateHeaders: true
                                        }
                                    });
                                }

                                integrationPapi.rules.children.push({
                                    name: 'behavior ' + papiName,
                                    children: [],
                                    behaviors: behaviors,
                                    criteria: [{
                                        name: 'path',
                                        options: {
                                            matchOperator: 'MATCHES_ONE_OF',
                                            values: [integrationUrlPathBehavior + url],
                                            matchCaseSensitive: false
                                        }
                                    }],
                                    criteriaMustSatisfy: 'all'
                                });
                            } else {
                                papiOpts.criteria[papiFilename] = opts;

                                integrationPapi.rules.children.push({
                                    name: 'criteria ' + papiName,
                                    children: [],
                                    behaviors: [{
                                        name: 'modifyOutgoingResponseHeader',
                                        options: {
                                            'action': 'MODIFY',
                                            'standardModifyHeaderName': 'OTHER',
                                            'customHeaderName': checkHeaderName,
                                            'newHeaderValue': checkHeaderValue,
                                            'avoidDuplicateHeaders': true
                                        }
                                    }],
                                    criteria: [{
                                        name: 'path',
                                        options: {
                                            matchOperator: 'MATCHES_ONE_OF',
                                            values: [integrationUrlPathCriteria + url],
                                            matchCaseSensitive: false
                                        }
                                    }, {
                                        name: papiName,
                                        options: opts
                                    }],
                                    criteriaMustSatisfy: 'all'
                                });
                            }
                        });

                        (0, _akamaiNginx.setLocalConfig)(_appRootPath2.default + '/test/_integration.template.json', // will load modified as integrationPapi
                        _appRootPath2.default + '/lua/akamai.lua');

                        _context.next = 9;
                        return (0, _akamaiNginx.generateConf)(integrationPapi);

                    case 9:
                        _context.next = 11;
                        return timeout(5000);

                    case 11:
                        return _context.abrupt('return', papiOpts);

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

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

var _mocha = require('mocha');

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _appRootPath = require('app-root-path');

var _appRootPath2 = _interopRequireDefault(_appRootPath);

var _globule = require('globule');

var _globule2 = _interopRequireDefault(_globule);

var _akamaiNginx = require('../src/akamai-nginx.js');

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

//lazy init
var papiOpts = {};
papiOpts.behavior = {};
papiOpts.criteria = {};

var integrationUrlPrefix = 'https://localhost';
var integrationUrlPathCriteria = '/integration/criteria/';
var integrationUrlPathBehavior = '/integration/behavior/';

var checkHeaderName = 'CRITERIA-TEST';
var checkHeaderValue = 'BEHAVIOR-TRIGGERED';

var variableCheckHeaderName = 'SETVARIABLE-RESULT';

// trigger config build before describe blocks
(0, _mocha.before)(function (done) {
    integrationConfig().then(function () {
        done();
    });
});

// todo use agent in supertest instead
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

function timeout(ms) {
    return new Promise(function (resolve) {
        return setTimeout(resolve, ms);
    });
}

function integrationTestUrl(papiJsonFileName, type, pathSuffix) {
    if (!pathSuffix) pathSuffix = '';
    if (!type || type !== 'criteria') {
        return integrationUrlPathBehavior + papiJsonFileName.replace('.papi.json', '') + pathSuffix + '?nocache=true';
    } else {
        return integrationUrlPathCriteria + papiJsonFileName.replace('.papi.json', '') + pathSuffix + '?nocache=true';
    }
}

module.exports.variableCheckHeaderName = variableCheckHeaderName;
module.exports.checkHeaderName = checkHeaderName;
module.exports.checkHeaderValue = checkHeaderValue;
module.exports.urlPrefix = integrationUrlPrefix;
module.exports.testUrl = integrationTestUrl;
module.exports.config = integrationConfig;