package de.thomasjacob.improve.presentation.project;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.project.Project;
import de.thomasjacob.improve.logic.project.ProjectDao;
import de.thomasjacob.improve.logic.user.User;
import de.thomasjacob.improve.presentation.ImproveAction;
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 ProjectRHAction 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");
		}

		ProjectForm projectForm = (ProjectForm) form;
		int projectId = projectForm.getProjectId().equals("") ? 0 : Integer.parseInt(projectForm.getProjectId());

		if (request.getParameter("Save") != null)
		{
			if (!validateAndAddErrors(form, request, mapping).isEmpty())
			{
				return mapping.findForward("success");
			}

			ProjectDao projectDao = DaoLocator.getInstance().getProjectDao();

			boolean nameExists = projectDao.isProjectNameExisting(projectForm.getName(), Integer.parseInt(projectForm
				.getProjectId()));
			if (nameExists)
			{
				getActionErrors(request)
					.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("ProjectRHAction.nameExists"));
				return mapping.findForward("success");
			}

			Project project = null;
			if (projectId == 0)
			{
				project = new Project();
			}
			else
			{
				project = projectDao.getProjectById(projectId);
			}

			project.setName(projectForm.getName());
			project.setEnabled(Boolean.parseBoolean(projectForm.getEnabled()));

			projectDao.saveInTransaction(project);
			request.setAttribute("projectId", new Integer(project.getId()));

			getActionMessages(request).add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("ProjectRHAction.saved"));
		}

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