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 Y42bNieValidator implements ConstraintValidator<Y42bNie, String> {

	private Pattern mask = Pattern.compile("[X-Z]\\d{7}[A-Z]");
	private static final int longitudCero = 0;

	@Override
	public void initialize(Y42bNie constraintAnnotation) {
	}

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

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

			Matcher matcher = mask.matcher(value);

			if (matcher.matches()) {
				if ('X' == value.charAt(0)) {
					value = value.replaceFirst("X", "0");
				} else if ('Y' == value.charAt(0)) {
					value = value.replaceFirst("Y", "1");
				} else if ('Z' == value.charAt(0)) {
					value = value.replaceFirst("Z", "2");
				}
				char letra = Y42bUtils.calcularLetraNIF(value);

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