package de.thomasjacob.improve.presentation.issue.edit;

import de.thomasjacob.improve.logic.DaoLocator;
import de.thomasjacob.improve.logic.issue.HistoryEntry;
import de.thomasjacob.improve.logic.issue.Issue;
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 de.thomasjacob.webcore.presentation.HtmlOption;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

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 IssueVPAction 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();

		User loggedInUser = LoginManager.getInstance(session).getUser();
		if (!LoginManager.getInstance(session).isLoggedIn())
		{
			return mapping.findForward("login");
		}
		NavigationFiller.getInstance().fill(mapping, request, session);

		IssueForm issueForm = IssueForm.getInstance(request);

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

		issueForm.setIssueId(String.valueOf(issueId));
		if (issueId == 0)
		{
			request.setAttribute("newIssue", Boolean.TRUE);
		}

		Issue issue = null;
		if (issueId != 0)
		{
			issue = DaoLocator.getInstance().getIssueDao().getIssueById(issueId);
		}

		if (issue == null || loggedInUser.mayEditIssue(issue.getProject()))
		{
			request.setAttribute("mayEditIssue", Boolean.TRUE);
		}

		if (loggedInUser.mayProcess(issue, false))
		{
			request.setAttribute("mayProcessIssue", Boolean.TRUE);
		}

		List projectIdOptions = new ArrayList();
		projectIdOptions.add(new HtmlOption("", "          "));

		List projects;
		if (issue != null)
		{
			projects = DaoLocator.getInstance().getProjectDao().findEnabledManagedProjects(loggedInUser);
		}
		else
		{
			projects = DaoLocator.getInstance().getProjectDao().findEnabledReportableProjects(loggedInUser);
		}

		if (issue != null && issue.getProject() != null && !projects.contains(issue.getProject()))
		{
			projects.add(0, issue.getProject());
		}

		if (projects.isEmpty())
		{
			getActionErrors(request).add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("IssueVPAction.missingProject"));
			return mapping.findForward("menu");
		}

		Iterator iterator = projects.iterator();
		while (iterator.hasNext())
		{
			Project project = (Project) iterator.next();
			projectIdOptions.add(new HtmlOption(String.valueOf(project.getId()), project.getName()));
		}
		Collections.sort(projectIdOptions);
		request.setAttribute("projectIdOptions", projectIdOptions);

		List developerOptions = new ArrayList();
		developerOptions.add(new HtmlOption("0", "-         "));
		List developers = DaoLocator.getInstance().getUserDao().findEnabledDevelopers();
		iterator = developers.iterator();
		while (iterator.hasNext())
		{
			User developer = (User) iterator.next();
			developerOptions.add(new HtmlOption(String.valueOf(developer.getId()), developer.getName()));
		}
		Collections.sort(developerOptions);
		request.setAttribute("developerOptions", developerOptions);

		if (request.getAttribute("doNotLoad") == null)
		{
			if (issue != null)
			{
				Project project = issue.getProject();
				issueForm.setProjectId(project != null ? String.valueOf(project.getId()) : "0");

				issueForm.setType(String.valueOf(issue.getType()));
				issueForm.setPriority(String.valueOf(issue.getPriority()));
				issueForm.setStatus(String.valueOf(issue.getStatus()));

				issueForm.setDeveloperId(issue.getDeveloper() != null ? String.valueOf(issue.getDeveloper().getId()) : "");

				issueForm.setName(issue.getName());
				issueForm.setDescription(issue.getDescription());
			}
			else
			{
				issueForm.setProjectId("0");
				issueForm.setType("");
				issueForm.setPriority("");
				issueForm.setStatus(String.valueOf(Issue.STATUS_NEW));
				issueForm.setDeveloperId("");
				issueForm.setName("");
				issueForm.setDescription("");
			}

			issueForm.setComment("");
		}

		if (issue != null)
		{
			Project project = issue.getProject();
			issueForm.setProjectName(project != null ? project.getName() : "");
			issueForm.setTypeName(issue.getTypeName());
			issueForm.setStatusName(issue.getStatusName());

			User reporter = DaoLocator.getInstance().getUserDao().getUserById(issue.getReporter().getId());
			issueForm.setReporterName(reporter.getName());

			if (issue.getDeveloper() != null)
			{
				issueForm.setDeveloperName(issue.getDeveloper().getName());
			}
			else
			{
				issueForm.setDeveloperName("-");
			}

			DateFormat dateFormat = DateFormat.getDateTimeInstance();

			IssueForm.HistoryEntry[] formHistoryEntries = new IssueForm.HistoryEntry[issue.getHistoryEntries().size()];
			ListIterator listIterator = issue.getHistoryEntries().listIterator(formHistoryEntries.length);
			for (int i=0; listIterator.hasPrevious(); i++)
			{
				HistoryEntry entry = (HistoryEntry) listIterator.previous();
				formHistoryEntries[i] = new IssueForm.HistoryEntry();
				formHistoryEntries[i].setComment(entry.getComment());
				formHistoryEntries[i].setDate(dateFormat.format(entry.getDate()));
				formHistoryEntries[i].setEditor(entry.getEditor().getName());
				formHistoryEntries[i].setStatus(entry.getStatusName());
			}
			issueForm.setHistoryEntries(formHistoryEntries);
		}
		else
		{
			issueForm.setProjectName("");
			issueForm.setTypeName("");
			issueForm.setStatusName("New");
			issueForm.setReporterName(loggedInUser.getName());
			issueForm.setDeveloperName("");
			issueForm.setHistoryEntries(new IssueForm.HistoryEntry[0]);
		}

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