const validationEl = {
    idsOfInputsWithNoNeedToUpdateDuringTyping: ['address-lookup-query', 'modal-address-lookup-query']
}

export function addFieldValidation(fieldSelector, validationFunction) {
    $(fieldSelector).each(function(index, element) {
        $(element).blur(function() {
            updateInputValueBeforeValidation(this);
             validationFunction(this);
             if (!validationEl.idsOfInputsWithNoNeedToUpdateDuringTyping.includes(element.id)) {
                $(this).keyup(function() {
                    updateInputValueBeforeValidation(this);
                    validationFunction(this);
                });
             }
        });
    });
}

export function updateInputValueBeforeValidation (element) {
    $(element).val($.trim($(element).val()));
}

export function validateEmail(element) {
    updateStylingError(element.id,
        isValidEmail(element.value),
        invalidEmailAddress);   
}

export function isValidEmail (value) {
    var ipAddressPattern = "(?:(?:25[0-5]|2[0-4][\\d]|[01]?[\\d][\\d]?)\\.){3}(?:25[0-5]|2[0-4][\\d]|[01]?[\\d][\\d]?)";
    var emailPattern = new RegExp("^[\\w\\+-]+(\\.[\\w\\+-]+)*@(([A-Za-z\\d]+[A-Za-z\\d-]*\\.){1,3}[A-Za-z]{2,16}|" + ipAddressPattern + ")$");
    return emailPattern.test(value);
}

export function validatePassword (element) {
    updateStylingError(element.id,
        isValidPassword(element.value),
        invalidPassword);
}

export function isValidPassword (value) {
    return value.length > 0;
}

export function validateTitle (element) {
    updateStylingError(element.id,
        isValidTitle(element.value),
        invalidTitle);
}

export function isValidTitle (value) {
    return value.length > 0; 
}

export function validateFirstName (element) {
    updateStylingError(element.id,
        isValidInputTextField(element.value),
        invalidFirstName);
}

export function validateLastName (element) {
    updateStylingError(element.id,
        isValidInputTextField(element.value),
        invalidLastName);
}

export function validateAddress1 (element) {
    updateStylingError(element.id,
        isValidInputTextField(element.value),
        invalidAddressOne);    
}

export function validateCity(element) {
    updateStylingError(element.id,
        isValidInputTextField(element.value),
        invalidTownCity);   
}

export function isValidFieldSize(value) {
    return value.length > 0 && value.length < 255;
}

export function isValidInputTextField(value) {
    var regExp = new RegExp("^[\\w ()/&.,'-]+$|^$");
    return isValidFieldSize(value) && regExp.test(value);
}

export function validateMobile (element, allowEmptyValue) {
    updateStylingError(element.id,
        isValidPhoneNumber(element.value, allowEmptyValue),
        invalidMobile);   
}

export function validatePhone(element) {
    updateStylingError(element.id,
        isValidPhoneNumber(element.value, true),
        invalidTelephone);    
}

export function isValidPhoneNumber(value,  allowEmptyValue) {
    var phonePatterElevenDigit = new RegExp("^0{1}\\d{10}$|^0{1}\\d{5}\\s{1}\\d{5}$|^0{1}\\d{4}\\s{1}\\d{6}$|^0{1}\\d{3}\\s{1}\\d{3}\\s{1}\\d{4}$|^0{1}\\d{2}\\s{1}\\d{4}\\s{1}\\d{4}$|^0{1}\\d{3}\\s{1}\\d{7}$");
    var phonePatternTenDigit = new RegExp("^0{1}\\d{9}$|^0{1}\\d{5}\\s{1}\\d{4}$|^0{1}\\d{4}\\s{1}\\d{5}$");
    var result = phonePatterElevenDigit.test(value) || phonePatternTenDigit.test(value);
    if (allowEmptyValue) {
        return value.length === 0 || result;
    } else {
        return value.length > 0 && result;
    }   
}

export function validatePostcode(element, ifConvert) {
    var elementValue = element.value;
    var isValid = isValidPostcodeField(elementValue);
    if (ifConvert && isValid) {
        elementValue = elementValue.replace(/\s/g, "");
        $('#' + $.escapeSelector(element.id))
            .val(elementValue.substr(0, elementValue.length-3) + " " + elementValue.substr(elementValue.length-3));
    }
    updateStylingError(element.id, isValid, invalidPostCode);
}

export function isValidPostcodeField(value) {
    var regExp = new RegExp("^[a-zA-Z0-9\\s]*$");
    return value.replace(/\s+/g, "").length > 4 && regExp.test(value);   
}

export function validateHouseName(element) {
    updateStylingError(element.id, isValidHouseName(element.value));

}

export function isValidHouseName(value) {
    var regExp = new RegExp("^[\\w ()/&.,'-]+$|^$");
    return value.length > 0 && regExp.test(value);
}

export function validateAddressSelection(element) {
    updateStylingError(element.id,
        isValidAddressSelection(element),
        selectAddressMessage);
}

export function isValidAddressSelection(element) {
    return !$('#' + $.escapeSelector(element.id)).is(":visible");

}

export function validateAddress2(element) {
    updateStylingError(element.id,
        isValidAddress2(element.value),
        invalidAddressTwo);  
}

export function isValidAddress2(value) {
    var regExp = new RegExp("^[\\w ().,'-]+$|^$");
    return value.length === 0 || regExp.test( value);  
}

export function validateVoucher(element) {
    updateStylingErrorForElement(element,
        isValidVoucher(element.value),
        invalidVoucherCode);  
}

export function isValidVoucher(value) {
    return value.trim().length > 0;
}

export function validateNameOnCard(element) {
    updateStylingError(element.id, true);
    var fieldSizeIsValid = isValidInputTextField(element.value);

    if (fieldSizeIsValid) {
        if (element.value.length > nameOnCardMaxLength) {
            updateStylingError(element.id, false, invalidNameOnCardLength);
        } else if(isNameOnCardContainsOnly16Digits(element.value)) {
            updateStylingError(element.id, false, invalidCustomNameOnCard);
        } else if(isNameOnCardContainsAtLeast14Digits(element.value)) {
            updateStylingError(element.id, false, validationWarnNameOnCard);
        }
    } else {
        updateStylingError(element.id, fieldSizeIsValid, invalidNameOnCard);
    }  
}


export function isNameOnCardContainsOnly16Digits(value) {
    var regExp = new RegExp("^\\d{16}$");
    return regExp.test(value);
}

export function isNameOnCardContainsAtLeast14Digits(value) {
    var regExp = new RegExp("^(.*\\d){14,}.*$");
    return regExp.test(value);  
}

export function validateStoreId(element) {
    updateStylingError(element.id,
        isValidStoreId(element.value),
        invalidStoreId);
}

export function isValidStoreId(value) {
    return value !== '0'; 
}

export function updateStylingError(elementId, isValid, errorMessage) {
    var element = $('#' + $.escapeSelector(elementId));
    updateStylingErrorForElement(element, isValid, errorMessage);   
}

export function updateStylingErrorForElement(element, isValid, errorMessage) {
    var parentElem = $(element).closest('.form-row');
    if (!parentElem.is(":visible")) {
        return;
    }
    removeErrorStyling(parentElem);
    if (!isValid) {
         wrapWithError(parentElem);
         addErrorMessage(parentElem, errorMessage);
    }
}

export function removeErrorStyling(element) {
    element.removeClass('form-row_validation-error');
    element.find('.form-row__error').remove();
}


export function wrapWithError(element) {
    $(element).addClass('form-row_validation-error');

}


export function addErrorMessage(element, errorMessage) {
    if (errorMessage) {
        $(element).append('<div class="form-row__error">' + errorMessage + '</div>');
    } 
}
