/*
 * $Id: ShowDocumentVersionsAction.java,v 1.19 2006/10/04 03:14:34 marbobo Exp $
 * 
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ShowDocumentVersionsAction.java,v $
 * Revision 1.19  2006/10/04 03:14:34  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.18  2006/08/30 21:08:15  marbobo
 * + Rückkehr zur Projekt- und Funktionssicht korrigiert
 *
 * Revision 1.17  2006/07/11 23:14:02  marbobo
 * + Dateien im Papierkorb werden nicht mehr im Quotaberechnung berücksichtigt
 * + Dokumentversionen werden nun beim aktivierten Papierkorb nicht mehr endgültig gelöscht
 *
 * Revision 1.16  2006/01/26 12:43:49  korowa
 * *** empty log message ***
 *
 * Revision 1.15  2006/01/20 12:43:24  korowa
 * Ermöglicht ein Vergleich von verschiedenen Versionen eines Dokumentes
 *
 * Revision 1.14  2005/02/08 15:27:36  jonyp
 * *** empty log message ***
 *
 *
 */
package vkc.view.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCDocument;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.procoba.project.ProjectViewForm;
import vkc.view.PageId;
import vkc.view.form.ShowDocumentVersionsForm;

/**
 * Action für die Wiedergabe eines Dokumentes aus dem Archiv
 *
 * @author koppy
 */
public final class ShowDocumentVersionsAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/common/ShowDocumentVersionsTemplate.jsp", false);

	/**
	 * Wird aufgerufen, falls die Versionen eines Documentes
	 * angezeigt werden soll(en)
	 */
	public ActionForward execute(ActionMapping mapping, 
								 ActionForm f,
								 HttpServletRequest request, 
								 HttpServletResponse response)
	throws ServletException {
		try {
			ShowDocumentVersionsForm form = (ShowDocumentVersionsForm) f;

			if (request.getParameter("action.back") != null) {
				return handleBackAction(form, request);
			} else if (request.getParameter("action.delete.document.version") != null) {
				return handleDeleteDocumentVersionAction(form, request);
			} else if (request.getParameter("action.show.document.details") != null) {
				return handleShowDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.hide.document.details") != null) {
				return handleHideDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.compare.documents") != null) {
				return handleCompareVersionsAction(form, request);
			} else {
				return handleInitialzeAction(form, request);
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}

	private ActionForward handleDeleteDocumentVersionAction(ShowDocumentVersionsForm form, HttpServletRequest request) throws Exception {
		if (form.isManageDocumentVersions() && form.getDeleteId() != null) {
			if (form.getDeleteId().equals(form.getDocumentId())) {
				Integer successorId = VKCDocumentSerializer.getSuccessorVersionDocId(form.getDeleteId());
				Integer predecessorId = VKCDocumentSerializer.getPredecessorVersionDocId(form.getDeleteId());

				if (successorId == null && predecessorId == null) {
					VKCDocumentSerializer.deleteDocumentVersion(form.getDeleteId(), form.getUser());
					form.setDocumentId(new Integer(-1));

					return handleBackAction(form, request);
				}

				if (successorId != null) {
					form.setDocumentId(successorId);
				} else {
					form.setDocumentId(predecessorId);
				}
			}

			VKCDocumentSerializer.deleteDocumentVersion(form.getDeleteId(), form.getUser());
		}

		return handleInitialzeAction(form, request);
	}

	private ActionForward handleCompareVersionsAction(ShowDocumentVersionsForm form, HttpServletRequest request) throws Exception {
		if (form.getSelectedDocuments().length == 2) {
			String forwardURL = "/compareVersions.do?initialize=true";

			return new ActionForward(forwardURL, false);
		}

		ActionErrors errors = new ActionErrors();
		errors.add("error.twoitem_checked", new ActionError("error.twoitem_checked"));
		saveErrors(request, errors);

		return handleInitialzeAction(form, request);
	}

	private ActionForward handleBackAction(ShowDocumentVersionsForm form, HttpServletRequest request) {
		String forwardURL = "";

		if (form.getSourcePageId().equals(PageId.PROJECT_VIEW)) {
			forwardURL = "/projectView.do?viewMode="
					+ ProjectViewForm.VIEW_MODE_FOLDER + "&projectId="
					+ form.getTargetId() + "&subfolderId="
					+ form.getSubTargetId() + "&anchor=doc"
					+ form.getDocumentId();

			return new ActionForward(forwardURL, true);
		} else if (form.getSourcePageId().equals(PageId.FUNCTIONAL_VIEW)) {
			forwardURL = "/functionalView.do?functionalViewId="
					+ form.getTargetId() + "&subfolderId="
					+ form.getSubTargetId() + "&anchor=doc"
					+ form.getDocumentId();

			return new ActionForward(forwardURL, true);
		} else if (form.getSourcePageId().equals(PageId.CATEGORY_VIEW)) {
			if (form.getTargetId() != null) {
				forwardURL = "/showCategory.do?categoryId="
						+ form.getTargetId() + "&anchor=doc"
						+ form.getDocumentId();
			} else {
				forwardURL = "/showCategory.do?categoryId="
						+ form.getCategoryId() + "&anchor=doc"
						+ form.getDocumentId();
			}

			return new ActionForward(forwardURL, true);
		} else {
			return new ActionForward("/showCategory.do?categoryId=" + VKCCategory.ROOT_CATEGORY_ID, true);
		}
	}

	private ActionForward handleHideDocumentDetailsAction(ShowDocumentVersionsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.remove(form.getSelectedId());
		form.setShowDocumentDetails((Integer[]) ids.toArray(new Integer[0]));
		VKCDocument doc = VKCDocumentSerializer.retrieveDocument(form.getDocumentId());
		form.setDocuments(doc.getAllVersions());

		return new ActionForward("/templates/${template.name}/common/ShowDocumentVersionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleShowDocumentDetailsAction(ShowDocumentVersionsForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.add(form.getSelectedId());
		form.setShowDocumentDetails((Integer[]) ids.toArray(new Integer[0]));
		VKCDocument doc = VKCDocumentSerializer.retrieveDocument(form.getDocumentId());
		form.setDocuments(doc.getAllVersions());

		return new ActionForward("/templates/${template.name}/common/ShowDocumentVersionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleInitialzeAction(ShowDocumentVersionsForm form, HttpServletRequest request) throws Exception {
		VKCDocument doc = VKCDocumentSerializer.retrieveDocument(form.getDocumentId());
		form.setCategoryId(doc.getCategoryId());
		form.setDocuments(doc.getAllVersions());

		return DEFAULT_FORWARD;
	}
}