package de.thomasjacob.improve.presentation.user;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.project.Project;
import de.thomasjacob.improve.logic.user.Role;
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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

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 UserVPAction 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");
		}

		UserForm userForm = UserForm.getInstance(request);
		User loggedInUser = LoginManager.getInstance(session).getUser();

		int userId;
		try
		{
			Object userIdParameter = request.getAttribute("userId");
			if (userIdParameter == null)
			{
				userIdParameter = request.getParameter("userId");
			}
			userId = Integer.parseInt(userIdParameter.toString());
		}
		catch (Exception e)
		{
			userId = 0;
		}

		boolean mayEditAccount = loggedInUser.isAdministrator() || loggedInUser.getId() == userId
			&& !loggedInUser.isGuest();
		if (!mayEditAccount)
		{
			getActionErrors(request).add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("LoginRHAction.priviledges"));
			return mapping.findForward("login");
		}

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

		User user;
		if (userId != 0)
		{
			user = DaoLocator.getInstance().getUserDao().getUserById(userId);
		}
		else
		{
			user = null;
		}

		List projects = DaoLocator.getInstance().getProjectDao().findProjects();

		List userProjectsWithRole = new ArrayList();
		List userProjectsWithoutRole = new ArrayList();
		Iterator iterator = projects.iterator();
		while (iterator.hasNext())
		{
			Project project = (Project) iterator.next();

			UserForm.Project userFormProject = new UserForm.Project();
			userFormProject = new UserForm.Project();
			userFormProject.setId(String.valueOf(project.getId()));
			userFormProject.setName(project.getName());

			if (user != null && user.getRole(project) != null)
			{
				userProjectsWithRole.add(userFormProject);
			}
			else
			{
				userProjectsWithoutRole.add(userFormProject);
			}
		}
		request.setAttribute("projectsWithRole", userProjectsWithRole);
		request.setAttribute("projectsWithoutRole", userProjectsWithoutRole);

		userForm.setUserId(String.valueOf(userId));
		userForm.setPassword1("");
		userForm.setPassword2("");
		if (request.getParameter("Save") == null)
		{
			if (userId != 0)
			{
				userForm.setEnabled(String.valueOf(user.isEnabled()));
				userForm.setAdministrator(String.valueOf(user.isAdministrator()));
				userForm.setGuest(String.valueOf(user.isGuest()));
				userForm.setEmail(user.getEmail());
				userForm.setName(user.getName());

				Set projectsWithoutRole = new HashSet(projects);
				List managerProjects = new ArrayList();
				List developerProjects = new ArrayList();
				List reporterProjects = new ArrayList();
				iterator = user.getRoles().values().iterator();
				while (iterator.hasNext())
				{
					Role role = (Role) iterator.next();
					projectsWithoutRole.remove(role.getProject());

					if (role.isManager())
					{
						managerProjects.add(String.valueOf(role.getProject().getId()));
					}
					if (role.isDeveloper())
					{
						developerProjects.add(String.valueOf(role.getProject().getId()));
					}
					if (role.isReporter())
					{
						reporterProjects.add(String.valueOf(role.getProject().getId()));
					}
				}
				userForm.setManagerProjects((String[]) managerProjects.toArray(new String[managerProjects.size()]));
				userForm.setDeveloperProjects((String[]) developerProjects.toArray(new String[developerProjects.size()]));
				userForm.setReporterProjects((String[]) reporterProjects.toArray(new String[reporterProjects.size()]));
			}
			else
			{
				userForm.setEnabled("");
				userForm.setAdministrator("");
				userForm.setGuest("");
				userForm.setEmail("");
				userForm.setName("");

				userForm.setManagerProjects(new String[0]);
				userForm.setDeveloperProjects(new String[0]);
				userForm.setReporterProjects(new String[0]);
			}
		}

		return mapping.findForward("success");
	}
}
