/* ===================================================================
 * RecipeSearchValidator.java
 * 
 * Created Nov 10, 2004 5:32:39 PM
 * 
 * Copyright (c) 2004 Matt Magoffin (spamsqr@msqr.us)
 * 
 * This program 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 2 of 
 * the License, or (at your option) any later version.
 * 
 * This program 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 this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
 * 02111-1307 USA
 * ===================================================================
 * $Id: RecipeSearchValidator.java 27 2009-05-03 23:40:50Z msqr $
 * ===================================================================
 */

package magoffin.matt.ieat.validation;

import magoffin.matt.ieat.biz.RecipeSearchBiz;
import magoffin.matt.ieat.domain.RecipeSearchCriteria;
import magoffin.matt.ieat.util.RecipeCommand;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Validator for RecipeCommand objects used for search actions.
 * 
 * @author Matt Magoffin (spamsqr@msqr.us)
 * @version $Revision: 27 $ $Date: 2009-05-04 11:40:50 +1200 (Mon, 04 May 2009) $
 */
public class RecipeSearchValidator implements Validator {

	/* (non-Javadoc)
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	public boolean supports(Class clazz) {
		return RecipeCommand.class.isAssignableFrom(clazz);
	}

	/* (non-Javadoc)
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	public void validate(Object obj, Errors errors) {
		RecipeCommand recipeCommand = (RecipeCommand)obj;
		if ( recipeCommand.getCriteria() == null ) return;
		RecipeSearchCriteria criteria = recipeCommand.getCriteria();
		
		if ( RecipeSearchBiz.RECIPE_SEARCH_MODE_SIMPLE.equals(criteria.getMode()) ) {
			if ( !StringUtils.hasText(criteria.getSimpleQuery()) ) {
				errors.rejectValue("criteria.simpleQuery","error.required",
						null,"name.displayName");
			}
		} else if ( RecipeSearchBiz.RECIPE_SEARCH_MODE_BY_INGREDIENT.equals(criteria.getMode()) ) {
			// FIXME verify ingredient is selected
		} else {
			if ( !StringUtils.hasText(criteria.getName()) ) {
				errors.rejectValue("criteria.name","error.required",
						null,"name.displayName");
			}
		}
	}

}
