package de.snailshell.consensus.demo.actions;

import java.util.Collection;
import java.util.Iterator;

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

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.uka.ipd.consensus.foundation.schema.User;
import de.uka.ipd.consensus.foundation.user.UserManager;
import de.uka.ipd.consensus.foundation.user.UserRole;
import de.uka.ipd.consensus.impl.UserImpl;

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

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

		if (!isUserLoggedOn(request)) {
			return mapping.findForward( Constants.MAPPING_FAILURE );			
		}

		if (!((UserImpl)getUser(request)).isSuperAdmin()) {
			return mapping.findForward( Constants.MAPPING_FAILURE );			
		}
		
		String username = request.getParameter("username");
		
		UserManager manager = this.getUserManager();
		
		User other = manager.getUserByUsername( username );
		
		Collection c = other.getRoles();

		String[] roles = new String[ c.size() ];
		
		Iterator it = c.iterator();
		
		int i = 0;
		
		while (it.hasNext()) {
			roles[i++] = ((UserRole)it.next()).getRolename();
		}

		((DynaActionForm)form).set( "selectedRoles", roles );
		((DynaActionForm)form).set( "username", username );

		request.setAttribute( Constants.REQUEST_ATTR_USER, other );

		return mapping.findForward( Constants.MAPPING_SUCCESS );
	}
}
