/**
 * 
 */
package es.dalocar.software.validator;

import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.log4j.Logger;

/**
 * Validator para tipos Integer
 * 
 * @author dlopez
 *
 */
public class IntegerValidator {
	
	private static Logger log = Logger.getLogger(IntegerValidator.class.getName());
	private static boolean DEBUG = log.isDebugEnabled();
	private static boolean INFO = log.isInfoEnabled();
	
	public static final String MINVALUE = "minvalue";
	public static final String MAXVALUE = "maxvalue";
	public static final String OTHER = "other";
	

	/**
	 * Valida el valor pasado dentro de un rango de enteros
	 * @param bean
	 * @param field
	 * @return
	 */
	public static boolean validateIntRange(Object bean, Field field) {
		boolean result = false;
        String value = ValidatorUtils.getValueAsString(bean, field
                .getProperty());
        
        if(GenericValidator.isInt(value)) {
        
	        int iValue = Integer.parseInt(value);
	        int minvalue = Integer.parseInt(field.getVarValue(MINVALUE));
	        int maxvalue = Integer.parseInt(field.getVarValue(MAXVALUE));
	
	        org.apache.commons.validator.routines.IntegerValidator ivalidator = 
	        	org.apache.commons.validator.routines.IntegerValidator.getInstance();
	        
	        result = ivalidator.isInRange(iValue, minvalue, maxvalue);
        }
        else{
        	result=true;
        }
		
		return result;
	}
	
	/**
	 * Valida que el valor pasado sea menor o igual al valor de otra de las propiedades del bean
	 * @param bean
	 * @param field
	 * @return
	 */
	public static boolean validateLessThan(Object bean, Field field) {
		boolean result = false;
		
        String value = ValidatorUtils.getValueAsString(bean, field.getProperty());                     
        String otherValue = ValidatorUtils.getValueAsString(bean, field.getVarValue(OTHER));
           
        if(DEBUG){
        	log.debug("String de prop1: " + value);
        	log.debug("String de other: " + otherValue);        	
        }
        
        if(GenericValidator.isInt(value) && GenericValidator.isInt(otherValue)) {
        
	        int iValue = Integer.parseInt(value);
	        int iOtherValue = Integer.parseInt(otherValue);	        
	        
	        if(DEBUG){
	        	log.debug("int de prop1: " + iValue);
	        	log.debug("int de prop2: " + iOtherValue);
	        }
	        
	        if(iValue<=iOtherValue){
	        	result=true;
	        }	        
        }
        else{
        	result=true;
        }
		
		return result;
	}

}
