/* ===================================================================
 * EditRecipeImageForm.java
 * 
 * Created Aug 14, 2005 3:30:29 PM
 * 
 * Copyright (c) 2005 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: EditRecipeImageForm.java 87 2009-05-18 22:44:24Z msqr $
 * ===================================================================
 */

package magoffin.matt.ieat.web;

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.EatValidationException;
import magoffin.matt.ieat.biz.BizContext;
import magoffin.matt.ieat.domain.Recipe;
import magoffin.matt.ieat.domain.UiData;
import magoffin.matt.ieat.domain.UiSearchResults;
import magoffin.matt.ieat.util.RecipeCommand;
import magoffin.matt.util.TemporaryFile;
import magoffin.matt.util.TemporaryFileMultipartFileEditor;

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

/**
 * Controller for adding/editing recipe image.
 * 
 * @author Matt Magoffin (spamsqr@msqr.us)
 * @version $Revision: 87 $ $Date: 2009-05-19 10:44:24 +1200 (Tue, 19 May 2009) $
 */
public class EditRecipeImageForm extends AbstractEatForm {

	/**
	 * Command class for edit recipe image form.
	 */
	public static class RecipeImageCommand extends RecipeCommand {
		private TemporaryFile image;
		private boolean removeImage = false;
		
		/**
		 * @return the image
		 */
		public TemporaryFile getImage() {
			return image;
		}
		
		/**
		 * @param image the image to set
		 */
		public void setImage(TemporaryFile image) {
			this.image = image;
		}
		
		/**
		 * @return the removeImage
		 */
		public boolean isRemoveImage() {
			return removeImage;
		}
		
		/**
		 * @param removeImage the removeImage to set
		 */
		public void setRemoveImage(boolean removeImage) {
			this.removeImage = removeImage;
		}
		
	}
	
	/**
	 * Validator for RecipeImageCommand objects.
	 */
	public static class RecipeImageCommandValidator implements Validator {

		/* (non-Javadoc)
		 * @see org.springframework.validation.Validator#supports(java.lang.Class)
		 */
		@SuppressWarnings("unchecked")
		public boolean supports(Class clazz) {
			return RecipeImageCommand.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) {
			RecipeImageCommand recipeCommand = (RecipeImageCommand)obj;
			
			if ( recipeCommand.getRecipeId() == null ) {
				errors.rejectValue("recipeId", "error.required", null, "recipe.id.displayName");
			}
			
			if ( recipeCommand.image == null && !recipeCommand.removeImage ) {
				errors.rejectValue("image", "error.required", null, "recipe.image.displayName");
			}
			
		}
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		WebUtil.getBizContext(request,true);
		
		Map<String, Object> m = new LinkedHashMap<String, Object>();
		
		UiData ui = getDomainObjectFactory().getUiDataInstance();
		m.put("uidata",ui);
		
		// add recipe
		RecipeCommand recipeCommand = (RecipeCommand)command;
		Recipe r = recipeBiz.getRecipeById(recipeCommand.getRecipeId());
		ui.getRecipe().add(r);
		
		if ( recipeCommand.getIndex() != null || recipeCommand.getCriteria() != null ) {
			UiSearchResults sr = getDomainObjectFactory().getEmbeddedSearchResultsInstance();
			WebUtil.initSearchResults(sr,recipeCommand.getIndex(),recipeCommand.getCriteria(), getDomainObjectFactory());
			ui.setSearchResults(sr);
		}
		return m;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		RecipeImageCommand recipeCommand = (RecipeImageCommand)command;
		BizContext context = WebUtil.getBizContext(request,true);
		
		if ( isCancel(request) ) {
			return processCancel(request,response,command,errors);
		}

		if ( recipeCommand.removeImage ) {
			// delete any existing image
			recipeBiz.removeRecipeImage(recipeCommand.getRecipeId(),context);
		} else {
			try {
				recipeBiz.storeRecipeImage(recipeCommand.getRecipeId(),recipeCommand.image,context);
			} catch ( EatValidationException e ) {
				Errors err = e.getErrors();
				for ( ObjectError oe : (List<ObjectError>)err.getAllErrors() ) {
					// FIXME this is terrible
					errors.rejectValue("image",oe.getCode(),oe.getArguments(),oe.getDefaultMessage());
				}
				return showForm(request,response,errors);
			}
		}
		
		Map<String, Object> model = new LinkedHashMap<String, Object>();
		WebUtil.saveRecipeCommand(model,recipeCommand);
		ModelAndView result = new ModelAndView(getSuccessView(),model);
		return result;
	}

	@Override
	protected ModelAndView processCancel(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors) {
		RecipeCommand recipeCommand = (RecipeCommand)command;
		Map<String, Object> model = new LinkedHashMap<String, Object>();
		WebUtil.saveRecipeCommand(model,recipeCommand);
		return new ModelAndView(getCancelView(),model);
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		
		// register our Multipart TemporaryFile binder...
		binder.registerCustomEditor(TemporaryFile.class, new TemporaryFileMultipartFileEditor(true));
	}
	
}
