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 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 ProjectVPAction 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);

		ProjectForm projectForm = ProjectForm.getInstance(request);

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

		projectForm.setProjectId(String.valueOf(projectId));
		if (request.getParameter("Save") == null)
		{
			if (projectId != 0)
			{
				Project project = DaoLocator.getInstance().getProjectDao().getProjectById(projectId);

				projectForm.setEnabled(String.valueOf(project.isEnabled()));
				projectForm.setName(project.getName());
			}
			else
			{
				projectForm.setEnabled("");
				projectForm.setName("");
			}
		}

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