package com.ejie.y42b.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import com.ejie.y42b.utils.Y42bUtils;

public class Y42bNifValidator implements ConstraintValidator<Y42bNif, String> {

	private Pattern mask = Pattern.compile("[0-9]{8,8}[A-Z]");
	private static final int longitudCero = 0;

	@Override
	public void initialize(Y42bNif constraintAnnotation) {
	}

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

		if (value == null || value.length() == Y42bNifValidator.longitudCero) {
			return true;
		} else {

			Matcher matcher = mask.matcher(value);

			if (matcher.matches()) {
				char letra = Y42bUtils.calcularLetraNIF(value);

				if (letra == value.charAt(value.length() - 1)) {
					return true;
				}
				return false;
			} else {
				return false;
			}
		}
	}
}