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 ChangeUserAction 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[] selectedRoles = (String[]) ((DynaActionForm)form).get( "selectedRoles" );
		String   username      = ((DynaActionForm)form).getString( "username" );

		UserManager manager = this.getUserManager();
		
		User other = manager.getUserByUsername( username );
		
		// add all selected roles:
		
		for (int i = 0; i < selectedRoles.length; i++) {
			other.addRole( manager.findRole(selectedRoles[i]) );
		}
		
		// delete all roles that are not selected:
		
		Collection all = manager.getRoles();
		
		Iterator it = all.iterator();
		
		_delete: while (it.hasNext()) {
			UserRole r = (UserRole)it.next();

			for (int i = 0; i < selectedRoles.length; i++) {
				if (r.getRolename().equals( selectedRoles[i] )) {
					continue _delete;
				}
			}
			
			other.removeRole( r );
		}

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