/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.xwork2.validator.validators;

import com.opensymphony.xwork2.validator.ValidationException;

/**
 * Base class for range based validators.
 */
public abstract class AbstractRangeValidator extends AbstractFieldValidator {

    /**
     * @see com.opensymphony.xwork2.validator.Validator#validate(java.lang.Object)
     */
	public void validate(Object object) throws ValidationException {
		Object obj = getFieldValue(getFieldName(), object);
		Comparable value = (Comparable) obj;

		// if there is no value - don't do comparison
		// if a value is required, a required validator should be added to the field
		if (value == null) {
			return;
		}

		// only check for a minimum value if the min parameter is set
		if ((getMinComparatorValue() != null) && (value.compareTo(getMinComparatorValue()) < 0)) {
			addFieldError(getFieldName(), object);
		}
		else if ((getMaxComparatorValue() != null)
				&& (value.compareTo(getMaxComparatorValue()) > 0)) {
			addFieldError(getFieldName(), object);
		}
	}

	protected abstract Comparable getMaxComparatorValue();

	protected abstract Comparable getMinComparatorValue();
}
