package net.contargo.types.telephony.validation;

import net.contargo.types.telephony.PhoneNumber;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

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 foundError = false;

        if (!StringUtils.isBlank(phoneNumber.getRawPhoneNumber())) {
            if (phoneNumber.containsOnlyZeros()) {
                reportConstraintViolation(cvc, "{ZERO_NUMBER}");
                foundError = true;
            }

            if (!phoneNumber.canBeFormatted()) {
                reportConstraintViolation(cvc, "{CAN_NOT_FORMATTED}");
                foundError = true;
            }

            if (phoneNumber.getRawPhoneNumber().length() > PHONE_NUMBER_SIZE) {
                reportConstraintViolation(cvc, "{TOO_LARGE}");
                foundError = true;
            }
        }

        return foundError;
    }


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

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

@@ -1130,16 +1130,32 @@
 (cvc, %22%7B
+PHONE_NUMBER_IS_
 ZERO_NUM
@@ -1158,24 +1158,24 @@
 _NUMBER%7D%22);%0A
-
             
@@ -1314,16 +1314,31 @@
 , %22%7B
+PHONE_NUMBER_
 CAN
-_
 NOT_
+BE_
 FORM
@@ -1473,24 +1473,24 @@
 BER_SIZE) %7B%0A
-
             
@@ -1526,16 +1526,29 @@
 (cvc, %22%7B
+PHONE_NUMBER_
 TOO_LARG

change message templates for phonenumber validator