/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 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.image.ImageWrapper;

import com.opensymphony.xwork2.validator.ValidationException;

/**
 * image size field validator.
 */
public class ImageSizeFieldValidator extends ImageFieldValidator {

	private Integer width;
	private Integer height;
	
	private Integer minWidth;
	private Integer minHeight;
	private Integer maxWidth;
	private Integer maxHeight;

	/**
	 * @return the width
	 */
	public Integer getWidth() {
		return width;
	}

	/**
	 * @return the height
	 */
	public Integer getHeight() {
		return height;
	}

	/**
	 * @return the minWidth
	 */
	public Integer getMinWidth() {
		return minWidth;
	}

	/**
	 * @param minWidth the minWidth to set
	 */
	public void setMinWidth(Integer minWidth) {
		this.minWidth = minWidth;
	}

	/**
	 * @return the minHeight
	 */
	public Integer getMinHeight() {
		return minHeight;
	}

	/**
	 * @param minHeight the minHeight to set
	 */
	public void setMinHeight(Integer minHeight) {
		this.minHeight = minHeight;
	}

	/**
	 * @return the maxWidth
	 */
	public Integer getMaxWidth() {
		return maxWidth;
	}

	/**
	 * @param maxWidth the maxWidth to set
	 */
	public void setMaxWidth(Integer maxWidth) {
		this.maxWidth = maxWidth;
	}

	/**
	 * @return the maxHeight
	 */
	public Integer getMaxHeight() {
		return maxHeight;
	}

	/**
	 * @param maxHeight the maxHeight to set
	 */
	public void setMaxHeight(Integer maxHeight) {
		this.maxHeight = maxHeight;
	}


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

		ImageWrapper img = getImage(value);
		if (img == null) {
			return;
		}

		width = img.getWidth();
		height = img.getHeight();
		
		if (minWidth != null && width < minWidth) {
			addFieldError(getFieldName(), object);
		}
		else if (minHeight != null && height < minHeight) {
			addFieldError(getFieldName(), object);
		}
		else if (maxWidth != null && width > maxWidth) {
			addFieldError(getFieldName(), object);
		}
		else if (maxHeight != null && height > maxHeight) {
			addFieldError(getFieldName(), object);
		}
	}
}
