package de.thomasjacob.improve.presentation.user;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.user.User;
import de.thomasjacob.improve.presentation.ImproveAction;
import de.thomasjacob.improve.presentation.NavigationFiller;
import de.thomasjacob.improve.presentation.login.LoginManager;
import de.thomasjacob.webcore.TechnicalException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
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.ActionMessage;
import org.apache.struts.action.ActionMessages;


public class UsersVPAction extends ImproveAction
{
	/*
	 * (non-Javadoc)
	 * 
	 * @see de.thomasjacob.webcore.presentation.BaseAction#executeChecked(org.apache.struts.action.ActionMapping,
	 * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	protected ActionForward executeChecked(ActionMapping mapping, ActionForm form, HttpServletRequest request,
		HttpServletResponse response) throws TechnicalException
	{
		HttpSession session = request.getSession();

		if (!LoginManager.getInstance(session).isLoggedIn())
		{
			return mapping.findForward("login");
		}

		User loggedInUser = LoginManager.getInstance(session).getUser();
		if (!loggedInUser.isAdministrator())
		{
			getActionErrors(request).add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("LoginRHAction.priviledges"));
			return mapping.findForward("login");
		}

		NavigationFiller.getInstance().fill(mapping, request, session);

		List viewUsers = new ArrayList();
		List userEntities = DaoLocator.getInstance().getUserDao().findUsers();
		Iterator usersIterator = userEntities.iterator();
		while (usersIterator.hasNext())
		{
			User user = (User) usersIterator.next();
			UserValueObject viewUser = new UserValueObject();

			viewUser.setUserId(user.getId());
			viewUser.setEnabled(user.isEnabled());
			viewUser.setType(user.getTypeName());
			viewUser.setName(user.getName());

			Map userParameters = new HashMap();
			userParameters.put("userId", new Integer(user.getId()));
			viewUser.setUserParameters(userParameters);

			viewUsers.add(viewUser);
		}

		request.setAttribute("users", viewUsers);
		return mapping.findForward("success");
	}
}