package managedbean.common;

/***
 * 
 * @author Marcos García Núñez (mgarcianun@uoc.edu)
 *
 */
public class ValidationUtils {
	static final String NIF_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE";
	static final String NIE_LETTERS = "XYZ";

	/**
	 * 
	 * @param nif NIF a validar
	 * @return true si es válido, false en otro caso
	 */
	public static boolean isValid(String nif) {
		if (nif == null)
			return false;

		nif = nif.toUpperCase().replace("-", "").replace(".", "");

		if (nif.length() < 2 || nif.length() > 9)
			return false;

		if (nif.startsWith("X")) {
			nif = nif.replace('X', '0');
		} else if (nif.startsWith("Y")) {
			nif = nif.replace('Y', '1');
		} else if (nif.startsWith("Z")) {
			nif = nif.replace('Z', '2');
		}

		char letra = nif.charAt(nif.length() - 1);
		if (NIF_LETTERS.indexOf(letra) < 0)
			return false;

		String numbers = nif.substring(0, nif.length() - 1);

		try {
			if (NIF_LETTERS.charAt(Integer.parseInt(numbers) % 23) == letra)
				return true;
		} catch (Exception ex) {
			return false;
		}

		return false;
	}

}
