/*
 * 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 nuts.core.lang.StringUtils;

import com.opensymphony.xwork2.validator.ValidationException;


/**
 * Compare field validator.
 */
public class CompareFieldValidator extends AbstractFieldValidator {

	private String target;
	private String comparator;

	/**
	 * @return the target
	 */
	public String getTarget() {
		return target;
	}

	/**
	 * @param target the target to set
	 */
	public void setTarget(String target) {
		this.target = target;
	}

	/**
	 * @return the comparator
	 */
	public String getComparator() {
		return comparator;
	}

	/**
	 * @param comparator the comparator to set
	 */
	public void setComparator(String comparator) {
		this.comparator = comparator;
	}


	/**
	 * @see com.opensymphony.xwork2.validator.Validator#validate(java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	public void validate(Object object) throws ValidationException {
		if (StringUtils.isEmpty(target)) {
			throw new ValidationException("target can not be empty");
		}
		
		Comparable targetValue = (Comparable)getFieldValue(target, object);
		Comparable fieldValue = (Comparable)getFieldValue(getFieldName(), object);

		if (fieldValue != null && targetValue != null) {
			int result = fieldValue.compareTo(targetValue);
			if ("eq".equals(comparator)) {
				if (result != 0) {
					addFieldError(getFieldName(), object);
				}
			}
			else if ("le".equals(comparator)) {
				if (result > 0) {
					addFieldError(getFieldName(), object);
				}
			}
			else if ("lt".equals(comparator)) {
				if (result >= 0) {
					addFieldError(getFieldName(), object);
				}
			}
			else if ("ge".equals(comparator)) {
				if (result < 0) {
					addFieldError(getFieldName(), object);
				}
			}
			else if ("gt".equals(comparator)) {
				if (result > 0) {
					addFieldError(getFieldName(), object);
				}
			}
			else {
				throw new ValidationException("Invalid comparator [" + comparator + "]. Please set one of these values [ 'eq', 'le', 'lt', 'ge', 'gt' ].");
			}
		}
	}
}
