package nl.quintor.commons.validator;

import java.util.Calendar;

import nl.quintor.commons.util.ValidatorMessages;
import nl.quintor.commons.util.ValidatorUtils;

/**
 * Validator for age verification. Through attributes (if registered properly in the faces-config.xml), the valid ages
 * can be customized.
 * 
 * @see ValidatorUtils#validateAge(Calendar, Integer, Integer)
 * @see AbstractValidator
 */
public class AgeValidator extends AbstractValidator {

	/**
	 * Minimum age the birth date should comply to.
	 */
	private Integer min = new Integer(0);

	/**
	 * Maximum age the birth date should comply to.
	 */
	private Integer max = new Integer(120);

	/**
	 * Constructor; sets a default value name for logging purposes.
	 */
	public AgeValidator() {
		super("Age");
	}

	/*
	 * (non-Javadoc)
	 * @see nl.achmea.avero.commons.validator.AbstractValidator#validate(java.lang.Object)
	 */
	protected String validate(final Object value) {
		return ValidatorUtils.validateAge((Calendar) value, min, max);
	}

	/**
	 * Returns the age limits according for the corresponding error code.
	 * 
	 * @see nl.quintor.commons.validator.AbstractValidator#getMessageParams(Object, String)
	 */
	@Override
	protected Object[] getMessageParams(final Object fieldValue, final String errorCode) {
		if (errorCode.equals(ValidatorMessages.VALIDATIONERROR_BIRTHDATE_TOOOLD)) {
			return new Object[] { max };
		} else if (errorCode.equals(ValidatorMessages.VALIDATIONERROR_BIRTHDATE_TOOYOUNG)) {
			return new Object[] { min };
		} else {
			return super.getMessageParams(fieldValue, errorCode);
		}
	}

	/**
	 * Bean setter for maximum age.
	 */
	public void setMax(Integer max) {
		this.max = max;
	}

	/**
	 * Bean setter for minimum age.
	 */
	public void setMin(Integer min) {
		this.min = min;
	}
}
