'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; 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 _behavior = require('../behavior.js');

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

var BehaviorSetVariable = exports.BehaviorSetVariable = function (_Behavior) {
    _inherits(BehaviorSetVariable, _Behavior);

    function BehaviorSetVariable(options, valueMap) {
        _classCallCheck(this, BehaviorSetVariable);

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

        _this.options = options;
        _this.valueMap = valueMap;
        return _this;
    }

    _createClass(BehaviorSetVariable, [{
        key: 'process',
        value: function process() {
            return ['varMap["' + this.options.variableName + '"] = function()', '\tlocal function setVar()'].concat(_toConsumableArray(this.setVariableLua(this.options).map(function (e) {
                return '\t\t' + e;
            })), ['\tend', '\treturn setVar()', 'end']);
        }
    }, {
        key: 'setVariableLua',
        value: function setVariableLua(options) {

            var lua = ['local result'];

            if (options.valueSource === 'EXPRESSION') {
                lua.push.apply(lua, ['-- EXPRESSION', 'result = swapVars("' + options.variableValue + '")']);
            }

            if (options.valueSource === 'GENERATE') {
                lua.push('-- GENERATE: ' + options.generator);
                lua.push.apply(lua, _toConsumableArray(this.switchByVal({
                    'RAND': ['math.randomseed(os.time())', 'result = math.random(' + options.minRandomNumber + ', ' + options.maxRandomNumber + ')']
                }, '-- not supported yet.', options.generator)));
            }

            if (options.valueSource === 'EXTRACT') {
                lua.push('-- EXTRACT: ' + options.extractLocation);
                lua.push.apply(lua, [this.switchByVal({
                    'COOKIE': 'result = cs(ngx.var["cookie_' + options.cookieName + '"])',

                    'CLIENT_REQUEST_HEADER': 'result = cs(ngx.req.get_headers()["' + options.headerName + '"])',

                    'QUERY_STRING': 'result = cs(ngx.req.get_uri_args()["' + options.queryParameterName + '"])',

                    'PATH_COMPONENT_OFFSET': 'result = cs(aka_request_uri_parts[' + options.pathComponentOffset + '])'

                }, '-- not supported yet.', options.extractLocation)]);
            }

            if (options.transform === 'NONE') {
                lua.push('return result');
            } else {
                lua.push.apply(lua, ['-- TRANSFORM: ' + options.transform, 'local options = { }']);

                Object.keys(options).forEach(function (key) {
                    lua.push('options["' + key + '"] = "' + options[key] + '"');
                });

                lua.push('return transformVariable(result, options)');
            }

            return lua;
        }
    }]);

    return BehaviorSetVariable;
}(_behavior.Behavior);

_behavior.Behavior.register('setVariable', BehaviorSetVariable);

/**
 * Option breakdown condensed from https://developer.akamai.com/api/luna/papi/behaviors.html#setvariable
 * ----------------------------
 {
  "variableName": "PMUSER_EXAMPLE_VAR_NAME",

  "valueSource" = GENERATE
    "generator":
        RAND + use "minRandomNumber", "maxRandomNumber"
        HEXRAND + use "numberOfBytes"

  valueSource = EXTRACT
    "extractLocation":
        COOKIE + use "cookieName"
        CLIENT_REQUEST_HEADER + use "headerName"
        QUERY_STRING + use "queryParameterName"
        PATH_COMPONENT_OFFSET + use "pathComponentOffset"

        CLIENT_CERTIFICATE=notsupported,
        EDGESCAPE=notsupported,
        PATH_COMPONENT_NAME=notsupported,
        PATH_PARAMETER=notsupported,

  valueSource = EXPRESSION
    "variableValue": "abc {{builtin.AK_HOST}} def"

  transform: common to all valueSource results
        NONE=do nothing
        ADD, SUBTRACT, MINUS, MULTIPLY, DIVIDE, MODULO + use "operandOne"
        LOWER, UPPER, STRING_LENGTH, REMOVE_WHITESPACE, TRIM
        SUBSTITUTE + use "regex", "replacement", "caseSensitive", "globalSubstitution"
            "replacement" supports group capture replacement via $1, $2 … $n
        SUBSTRING + use "startIndex", "endIndex"
        STRING_INDEX + use "subString"
        URL_ENCODE + use "exceptChars", "forceChars"
        HEX_ENCODE, HEX_DECODE, XML_ENCODE, XML_DECODE, URL_DECODE, URL_DECODE_UNI, NORMALIZE_PATH_WIN
        BITWISE_AND, BITWISE_OR, BITWISE_XOR + use "operandOne"
        BITWISE_NOT
        DECIMAL_TO_HEX, HEX_TO_DECIMAL
        DECRYPT/ENCRYPT, + use "algorithm", "encryptionKey", "initializationVector",
            "encryptionMode(CBC/ECB", "nonce", "prependBytes"
            (ALG_AES128 or ALG_AES256 (Advanced Encryption Standard, 128 or 256 bits), or ALG_3DES)
        BASE_64_ENCODE/BASE_64_DECODE
        SHA_1, SHA_256, MD5, a base64-encoded HMAC key, or a simple HASH
            HMAC + use "hmacKey", "hmacAlgorithm" (MD5, SHA1, or SHA256) - HASH + use "min", "max"
        UTC_SECONDS (epoch time), EPOCH_TO_STRING, and STRING_TO_EPOCH + use "formatString"
            %m/%d/%y as specified by strftime
        NETMASK + use "ipVersion" (IPV4 or IPV6), "ipv6Prefix", "ipv4Prefix"
        EXTRACT_PARAM + use "paramName", "separator"



} **/