package de.snailshell.consensus.demo.actions;

import java.util.HashMap;
import java.util.Map;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import de.snailshell.consensus.demo.Constants;
import de.snailshell.consensus.demo.exceptions.RegisterPasswordException;
import de.uka.ipd.consensus.foundation.schema.User;
import de.uka.ipd.consensus.foundation.user.UserManager;
import de.uka.ipd.consensus.impl.UserManagerImpl;

/**
 * @author Thomas Much
 * @version 2006-06-14
 */
public class RegisterAction extends BasisAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String benutzername = ((DynaActionForm)form).getString("benutzername");
		String passwort1    = ((DynaActionForm)form).getString("passwort1");
		String passwort2    = ((DynaActionForm)form).getString("passwort2");
		String vorname      = ((DynaActionForm)form).getString("vorname");
		String nachname     = ((DynaActionForm)form).getString("nachname");
		String email        = ((DynaActionForm)form).getString("email");
		
		if (!passwort1.equals(passwort2)) {
			throw new RegisterPasswordException();
		}

		UserManager manager = this.getUserManager();
		
		Map data = new HashMap();

		data.put( UserManagerImpl.USERDATA_FIRSTNAME_KEY, vorname );
		data.put( UserManagerImpl.USERDATA_LASTNAME_KEY, nachname );
		data.put( UserManagerImpl.USERDATA_EMAIL_KEY, email );

		User user = manager.createUser(benutzername,passwort1,data);
		
		// no exception, "user" valid
		
		HttpSession session = request.getSession(false);

		if (session != null) {
			session.invalidate();
		}

		session = request.getSession(true);

		session.setAttribute(Constants.SESSION_ATTR_USER, user);

		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}

}
