"use strict";

module.exports = {
    getValidatorObj: function (dataFields) {
        var validationObj = {};
        if (this.hasValue(dataFields) && dataFields.fieldValidator &&
            dataFields.fieldValidator.validationFunc && dataFields.fieldValidator.validationMsg) {

            // disable warning about use of Function. This is because using dynamically loaded code isn't seen as a good thing.
            // we're doing it to load the code from the template but wouldn't do it for normal file scripts
            /* jshint -W054 */
            validationObj.validationFunc = new Function("value", dataFields.fieldValidator.validationFunc);
            /* jshint +W054 */

            validationObj.validationMsg = dataFields.fieldValidator.validationMsg;
            validationObj.name = dataFields.fieldValidator.name;
        }
        return validationObj;
    },

    hasValidateFunc: function (field) {
        var validateObj = this.getValidatorObj(field);
        return validateObj.validationFunc ? true : false;
    },

    validateFieldValue: function (field) {
        var res = false;
        var validateObj = this.getValidatorObj(field);
        if (validateObj.validationFunc && field.fieldValue) {
            var validatorFunc = validateObj.validationFunc;
            res = validatorFunc(field.fieldValue);
        }
        return res;
    },

    /*
     * Validate field value, if the validation get errors, the validator name will be returned. Otherwise, return null.
     */
    validateField: function(validator, newValue) {
        var res = true;
        if (validator.validationFunc) {
            var validatorFunc = validator.validationFunc;
            res = validatorFunc(newValue);
        }
        return res === false ? validator.name : null;

    },

    hasValue: function (val) {
        return val !== null && typeof(val) !== "undefined" && val !== "";
    },

    validateMinLength: function(val, minLength) {
        return this.hasValue(val) && val.length >= minLength;
    },

    validateMaxLength: function(val, maxLength) {
        return !val || this.hasValue(val) && val.length <= maxLength;
    }
};
