"use strict";
/**
 * Helper module for matching conditions
 * Ported from https://github.com/optimizely/client-js/blob/5025fb16720e35213b822c0e673a265d24ae4bff/src/core/lib/match.js
 * @module
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasMatch = void 0;
const error_1 = require("./error");
/**
 * Returns true if the value matches the  string
 * as defined by 'match' (ex: exists/exact/substring/regex)
 *
 * @param {string} value
 * @param {string} match
 * @param {null|string|number} visitorValue
 * @return {boolean}
 */
function hasMatch(value, match, visitorValue) {
    var isUserValueDefined = typeof visitorValue !== 'undefined' && visitorValue !== null;
    var isConditionValueDefined = typeof value !== 'undefined' && value !== null;
    var matchType = match || (isConditionValueDefined ? 'exact' : 'exists');
    switch (matchType) {
        case 'exists':
            return isUserValueDefined;
        case 'exact':
            return isUserValueDefined && String(visitorValue) === value;
        case 'substring':
            return (isUserValueDefined && String(visitorValue).indexOf(value) > -1);
        case 'regex':
            try {
                if (isConditionValueDefined && isUserValueDefined) {
                    var regex = new RegExp(value);
                    return regex.test(String(visitorValue));
                }
                return false;
            }
            catch (error) {
                let newError = new error_1.MatchError(`Error evaluating regex value: ${value}`);
                console.log(newError);
                // TODO: log this to honeycomb
                // logger.logError(newError);
            }
            return false;
        case 'range':
            // TODO(tyler): refactor?
            // range match type is currently used only by third-party dimensions
            var rangeValues = value.split(':');
            var fromValue = parseFloat(rangeValues[0]);
            var toValue = parseFloat(rangeValues[1]);
            var currentValue = parseFloat(visitorValue);
            return currentValue >= fromValue && currentValue <= toValue;
        default:
            return false;
    }
}
exports.hasMatch = hasMatch;
