/* ===================================================================
 * AddIngredientForm.java
 * 
 * Copyright (c) 2004 Matt Magoffin. Created Aug 18, 2004 7:03:26 PM.
 * 
 * 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: AddIngredientForm.java 28 2009-05-04 01:19:45Z msqr $
 * ===================================================================
 */

package magoffin.matt.ieat.web;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import magoffin.matt.ieat.biz.BizContext;
import magoffin.matt.ieat.domain.Ingredient;
import magoffin.matt.ieat.domain.UiData;
import magoffin.matt.ieat.domain.UiEdit;
import magoffin.matt.ieat.domain.UiIngredientMatch;
import magoffin.matt.ieat.domain.UiSearchResults;
import magoffin.matt.ieat.util.IngredientCriteriaImpl;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller for adding a new ingredient.
 * 
 * @author Matt Magoffin (spamsqr@msqr.us)
 * @version $Revision: 28 $ $Date: 2009-05-04 13:19:45 +1200 (Mon, 04 May 2009) $
 */
public class AddIngredientForm extends AbstractEatWizardForm {

	@Override
	@SuppressWarnings("unchecked")
	protected Map referenceData(HttpServletRequest request, int page)
	throws Exception  {
		Map<String, Object> m =  new LinkedHashMap<String, Object>();
		UiData ui = getDomainObjectFactory().getUiDataInstance();
		m.put("uidata",ui);

		List<Ingredient> l = recipeBiz.getAvailableIngredients();
		ui.getIngredient().addAll(l);
		return m;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
	throws Exception 
	{
		UiEdit edit = getDomainObjectFactory().getUiEditInstance();
		Ingredient ingredient = getDomainObjectFactory().getIngredientInstance();
		edit.setIngredient(ingredient);
		
		ServletRequestDataBinder binder = createBinder(request, edit);
		binder.bind(request);
		
		return edit;
	}
	
	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception 
	{
		// store recipe in backend!
		UiEdit edit = (UiEdit)command;
		Ingredient ingredient = edit.getIngredient();
		BizContext context = WebUtil.getBizContext(request, false);
		ingredient = recipeBiz.storeIngredient(ingredient,context);
		edit.setIngredient(ingredient);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(WebConstants.DEFALUT_MODEL_OBJECT, edit);
		return new ModelAndView(getSuccessView(),params);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void validatePage(Object command, Errors errors, int page) {
		UiEdit edit = (UiEdit)command;
		Ingredient ingredient = edit.getIngredient();
		Validator val = getValidator();
		val.validate(ingredient, errors);
		
		// as long as there are no other validation errors, validate not similar to other 
		// ingredient names already available
		if ( page == 0 && errors.getErrorCount() < 1 && !edit.isIgnoreWarnings() 
				&& ingredient.getName() != null && ingredient.getName().trim().length() > 0 ) {
			// search for like-named recipes and display validation error if any found
			IngredientCriteriaImpl criteria = new IngredientCriteriaImpl(ingredient.getName());
			UiSearchResults results = recipeSearchBiz.findIngredientsSimilarlyNamed(criteria);
			if ( results.getTotalResults().intValue() > 0 ) {
				for ( UiIngredientMatch match : (List<UiIngredientMatch>)results.getIngredient() ) {
					errors.rejectValue("ingredient.name", "edit-ingredient.similar.name", 
							new Object[] {match.getName()}, "name.displayName");
				}
				edit.setIgnoreWarnings(true);
			}
		}
	}
	
}
