package de.thomasjacob.improve.presentation.project;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.project.Project;
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 ProjectsVPAction 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 viewProjects = new ArrayList();
		List projectEntities = DaoLocator.getInstance().getProjectDao().findProjects();
		Iterator projectsIterator = projectEntities.iterator();
		while (projectsIterator.hasNext())
		{
			Project project = (Project) projectsIterator.next();
			ProjectValueObject viewProject = new ProjectValueObject();

			viewProject.setProjectId(project.getId());
			viewProject.setEnabled(project.isEnabled());
			viewProject.setName(project.getName());

			Map projectParameters = new HashMap();
			projectParameters.put("projectId", new Integer(project.getId()));
			viewProject.setProjectParameters(projectParameters);

			viewProjects.add(viewProject);
		}

		request.setAttribute("projects", viewProjects);
		return mapping.findForward("success");
	}
}