/* ===================================================================
 * AddUserForm.java
 * 
 * Created Nov 18, 2004 7:07:14 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: AddUserForm.java 28 2009-05-04 01:19:45Z 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.AuthorizationException;
import magoffin.matt.ieat.EatValidationException;
import magoffin.matt.ieat.biz.BizContext;
import magoffin.matt.ieat.domain.UiEdit;
import magoffin.matt.ieat.domain.User;

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

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

	@Override
	protected ModelAndView processCancel(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception 
	{
		UiEdit edit = (UiEdit)command;
		Map<String, Object> model = new LinkedHashMap<String, Object>();
		WebUtil.saveUserEdit(model,edit);
		return new ModelAndView(getCancelView(),model);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception 
	{
		getBizContext(request); // verify user context
		UiEdit edit = getDomainObjectFactory().getUiEditInstance();
		User user = getDomainObjectFactory().getUserInstance();
		edit.setUser(user);
		return edit;
	}
	
	/**
	 * Get a BizContext for this action.
	 * 
	 * <p>This method exists so extending classes can customize the 
	 * desired behavior, for example this method calls the 
	 * {@link WebUtil#getAdminBizContext(HttpServletRequest, magoffin.matt.ieat.biz.UserBiz)}
	 * method but others may not need an admin context.</p>
	 * 
	 * @param request the current request
	 * @return a BizContext
	 */
	protected BizContext getBizContext(HttpServletRequest request) {
		return WebUtil.getAdminBizContext(request,userBiz);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView processFinish(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception 
	{
		// store user in backend!
		UiEdit edit = (UiEdit)command;
		User user = edit.getUser();
		BizContext context = getBizContext(request);
		try {
			user = userBiz.storeUser(user,context);
		} catch ( AuthorizationException e ) {
			switch ( e.getReason() ) {
				case AuthorizationException.DUPLICATE_LOGIN:
					errors.rejectValue("user.login", "user.error.login.taken", 
							new Object[] {user.getLogin()}, "login.displayName");
					return showPage(request,errors,getInitialPage(request));
				
				case AuthorizationException.DUPLICATE_EMAIL:
					errors.rejectValue("user.email", "user.error.email.taken", 
							new Object[] {user.getEmail()}, "email.displayName");
					return showPage(request,errors,getInitialPage(request));
			}
		} catch ( EatValidationException e ) {
			Errors err = e.getErrors();
			for ( ObjectError oe : (List<ObjectError>)err.getAllErrors() ) {
				// FIXME this is terrible
				errors.rejectValue(oe.getObjectName(),oe.getCode(),oe.getArguments(),oe.getDefaultMessage());
			}
			return showPage(request,errors,getCurrentPage(request)-1);
		}
		
		Map<String, Object> model = new LinkedHashMap<String, Object>();
		WebUtil.saveUserEdit(model,edit);
		return new ModelAndView(getSuccessView(),model);
	}
	
	@Override
	protected void validatePage(Object command, Errors errors, int page) 
	{
		Validator v = getValidator(); // no need for paged validation really
		User user = ((UiEdit)command).getUser();
		v.validate(user,errors);
	}

}
