/**
 * 
 */
package org.yacos.web.system.controller;

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

import org.acegisecurity.providers.dao.UserCache;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
import org.yacos.core.exceptions.PKAlreadyUsedException;
import org.yacos.core.exceptions.UserEMailAlreadyExistsException;
import org.yacos.core.users.IUserManager;
import org.yacos.core.users.User;
import org.yacos.web.system.form.FormUser;
import org.yacos.web.system.session.SessionService;

/**
 * FormController class for the user Sign In scenario (user registration)
 * 
 * TODO: implement the invitation system
 * 
 * @author christiancorsano
 *
 */
public class SUserRegistrationController extends SimpleFormController {
	private IUserManager userManager;
	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors) {
		FormUser userCommand = (FormUser) command;
		
		// Tries to retrieve the current user : case of user modification
		User user = SessionService.getInstance().getCurrentUser();
		
		if( userCommand.getIsNew() ){
			try {
				userManager.addUser(
						userCommand.getLogin(),
						User.hashPassword(userCommand.getPassword()),
						userCommand.getFirstName(),
						userCommand.getLastName(),
						userCommand.getOrganization(),
						userCommand.getEmail());
			} catch (PKAlreadyUsedException e) {
				errors.rejectValue("login", "form.register.error.alreadyExists");
				return new ModelAndView(new RedirectView(getFormView()));
			} catch (UserEMailAlreadyExistsException e) {
				errors.rejectValue("email", "form.register.error.alreadyExists");
				return new ModelAndView(new RedirectView(getFormView()));
			}
		} else {
			user.setEmail(userCommand.getEmail());
			user.setFirstName(userCommand.getFirstName());
			user.setLastName(userCommand.getLastName());
			user.setOrganization(userCommand.getOrganization());
			
			if(userCommand.passwordWasModified()){
				user.setPassword(User.hashPassword(userCommand.getPassword()));
			}
			
			userManager.UpdateUser(user);
			
			// Empty cache
			//UserCache.removeUserFromCache(user.getLogin());
		    
		}
		
		return new ModelAndView(new RedirectView(getSuccessView()));
	}

	/**
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		FormUser user = new FormUser();
		
		// We try to see if the user is already registered and logged
		User currentUser = new User();
		user.setIsNew(true);
		// TODO : see how JAAS could change the way of getting the current User
		if(SessionService.getInstance().isUserLogged()){
			// If he is logged, we use his profile information to fill the form
			currentUser = (User) SessionService.getInstance().getCurrentUser();
			user.setIsNew(false);
		}
		
		user.setLogin(currentUser.getLogin());
		user.setFirstName(currentUser.getFirstName());
		user.setLastName(currentUser.getLastName());
		user.setEmail(currentUser.getEmail());
		user.setOrganization(currentUser.getOrganization());
		
		return user;
	}
	
	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}
	
	public IUserManager getUserManager() {
		return userManager;
	}
}
