package net.contargo.types.telephony.validation;

import net.contargo.types.telephony.PhoneNumber;

import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


/**
 * Validates whether the provided string is a valid phone number.
 *
 * @author  Robin Jayasinghe - jayasinghe@synyx.de
 * @author  Olle Törnström - toernstroem@synyx.de
 */
public class ValidPhoneNumberValidator implements ConstraintValidator<ValidPhoneNumber, String> {

    private static final int PHONE_NUMBER_SIZE = 64;

    @Override
    public void initialize(ValidPhoneNumber a) {
    }


    @Override
    public boolean isValid(String value, ConstraintValidatorContext cvc) {

        if (StringUtils.isEmpty(value)) {
            return true;
        }

        final PhoneNumber phoneNumber = new PhoneNumber(value);

        boolean isValid = true;

        if (!StringUtils.isBlank(phoneNumber.getRawPhoneNumber())) {
            if (phoneNumber.containsOnlyZeros()) {
                reportConstraintViolation(cvc, "{PHONE_NUMBER_IS_ZERO_NUMBER}");
                isValid = false;
            }

            if (!phoneNumber.canBeFormatted()) {
                reportConstraintViolation(cvc, "{PHONE_NUMBER_CANNOT_BE_FORMATTED}");
                isValid = false;
            }

            if (phoneNumber.getRawPhoneNumber().length() > PHONE_NUMBER_SIZE) {
                reportConstraintViolation(cvc, "{PHONE_NUMBER_TOO_LARGE}");
                isValid = false;
            }

            if (!phoneNumber.isValidNumber()) {
                reportConstraintViolation(cvc, "{PHONE_NUMBER_VALID}");
                isValid = false;
            }
        }

        return isValid;
    }


    private void reportConstraintViolation(final ConstraintValidatorContext context, final String messageTemplate) {

        context.buildConstraintViolationWithTemplate(messageTemplate).addConstraintViolation();
    }
}

@@ -43,16 +43,52 @@
 ation;%0A%0A
+import net.contargo.types.Loggable;%0A
 import n
@@ -546,16 +546,26 @@
  String%3E
+, Loggable
  %7B%0A%0A    
@@ -1655,41 +1655,165 @@
     
-reportConstraintViolation(cvc, %22%7B
+// TODO: to be discussed if the phone numbers has to be validated harder. currently only log info if the number is not valid.%0A                logger().info(%22
 PHON
@@ -1825,49 +1825,109 @@
 BER_
+IN
 VALID
-%7D%22);%0A                isValid = false
+ - the given number '%7B%7D' ist not valid!%22,%0A                    phoneNumber.getRawPhoneNumber())
 ;%0A  

make validation check weaker