/*
 * $Id: FunctionalViewAction.java,v 1.1 2006/10/04 03:15:14 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: FunctionalViewAction.java,v $
 * Revision 1.1  2006/10/04 03:15:14  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.20  2006/07/12 23:49:34  marbobo
 * + Zurück-Button implementiert
 *
 * Revision 1.19  2006/07/03 23:46:32  marbobo
 * + Neu implementierung der Projekt- und Funktionssicht-Tabs
 *
 * Revision 1.18  2006/05/31 18:15:43  marbobo
 * + Bugfix
 *
 * Revision 1.17  2006/05/15 13:01:02  marbobo
 * + Fehlermeldung falls keine Funktionssicht verfügbar
 *
 * Revision 1.16  2006/02/27 16:16:24  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.15  2005/09/22 13:18:20  marbobo
 * + Bugfix beim löschen von Kategorien und Dokumenten
 *
 * Revision 1.14  2005/09/01 16:31:31  jonyp
 * changes due to new signature of VKCCategory.deleteCategory/VKCDocument.deleteDocument
 *
 * Revision 1.13  2005/08/26 14:54:29  jonyp
 * changes due to new paramter(user) for deleteDocument
 *
 * Revision 1.12  2004/11/10 15:02:53  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.11  2004/10/31 03:04:25  marbobo
 * + Verbesserungen und Bugfixes
 *
 * Revision 1.10  2004/07/27 14:56:06  jonyp
 * added new parameter for deletion of categories (definite = true)
 *
 * Revision 1.9  2004/07/20 08:58:38  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.procoba.function;

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

import org.apache.struts.action.Action;
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.VKCEntity;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.security.PermissionManager;
import vkc.util.StrutsUtils;
import vkc.view.WebShare;

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

public class FunctionalViewAction extends Action {
	private ActionForward DEFAULT_FORWARD =	new ActionForward("/templates/${template.name}/procoba/function/FunctionalView.jsp", false);

	public ActionForward execute(ActionMapping mapping,
								 ActionForm f,
								 HttpServletRequest request,
								 HttpServletResponse response)
	throws ServletException {
		try {
			FunctionalViewForm form = (FunctionalViewForm)f;			
			
			if (!VKCSysParameterSerializer.isProjectManagementEnabled()) {
				return new ActionForward("/showCategory.do?categoryId=" + VKCCategory.ROOT_CATEGORY_ID, true);
			}

			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.delete.document") != null) {
				return handleDeleteDocumentAction(form, request);
			} else if (request.getParameter("action.change.category.sortmode") != null) {
				return handleCategoryChangeSortMode(form, request);
			} else if (request.getParameter("action.change.document.sortmode") != null) {
				return handleDocumentChangeSortMode(form, request);
			} else if (request.getParameter("action.delete.subfolder") != null) {
				return handleDeleteSubfolder(form, request);
			} else if (request.getParameter("action.back.to.parentsubfolder") != null) {
				return handleBackToParentSubfolderAction(form);
            } else {
				return handleInitializeAction(form, request);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	protected ActionForward handleBackToParentSubfolderAction(FunctionalViewForm form) throws DBException {
		return new ActionForward("/functionalView.do" +
				 				 "?functionalViewId=" + form.getFunctionalViewId() +
				 				 "&subfolderId=" + form.getParentCategoryId(),
				 				 true);
	}

	protected ActionForward handleInitializeAction(FunctionalViewForm form, HttpServletRequest request) throws DBException {
		if (request.getParameter("sysLinkMessageKey") != null) {
			request.setAttribute(WebShare.INFO_KEY, request.getParameter("sysLinkMessageKey"));
		}
		
		if (VKCEntity.ID_UNDEFINED.equals(form.getFunctionalViewId())
		   || WebShare.getCategorySettings().getProjectManagementRootId().equals(form.getFunctionalViewId())) {
			List functionInfos = FunctionalViewUtils.getFunctionalViewInfos(form.getUser());
			
			if (functionInfos.size() > 0) {
				FunctionalViewInfo info = (FunctionalViewInfo)functionInfos.get(0);
				form.setFunctionalViewId(info.getCategoryId());
				form.setSubfolderId(info.getCategoryId());
			} else {
				StrutsUtils.addErrorMessage(request, "function.info.no.functions");
				form.setFunctionalViewId(VKCEntity.ID_UNDEFINED);
				form.setSubfolderId(VKCEntity.ID_UNDEFINED);
			}
		}
		
		return DEFAULT_FORWARD;
	}

	protected ActionForward handleCategoryChangeSortMode(FunctionalViewForm form, HttpServletRequest request) {
		return new ActionForward("/templates/${template.name}/procoba/function/FunctionalView.jsp?anchor=categorysortbar", false);
	}

	protected ActionForward handleDocumentChangeSortMode(FunctionalViewForm form, HttpServletRequest request) {
		return new ActionForward("/templates/${template.name}/procoba/function/FunctionalView.jsp?anchor=documentsortbar", false);
	}

	protected ActionForward handleHideDocumentDetailsAction(FunctionalViewForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.remove(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));
		
		return new ActionForward("/templates/${template.name}/procoba/function/FunctionalView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	protected ActionForward handleShowDocumentDetailsAction(FunctionalViewForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.add(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));

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

	protected ActionForward handleDeleteDocumentAction(FunctionalViewForm form, HttpServletRequest request) throws ServletException {
		try {
			if (!PermissionManager.hasPermission(form.getCategory().getAcl(), form.getUser(), 'd')) {
				StrutsUtils.addInfoMessage(request, "project.info.delete.doc.denied");
				
				return DEFAULT_FORWARD;
			}

			VKCDocumentSerializer.deleteDocument(form.getUser(), form.getSelectedId(), !WebShare.isTrashEnabled(), null);

			return DEFAULT_FORWARD;
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}
	
	/**
	 * Methode löscht ein Subfolder
	 */
	protected ActionForward handleDeleteSubfolder(FunctionalViewForm form, HttpServletRequest request) throws ServletException {
		try {
			if (form.isFunctionalViewRootCategory()) {
				request.setAttribute(WebShare.INFO_KEY, "vkc.info.root.not.deletable");
			    
				return DEFAULT_FORWARD;
			} else if (!PermissionManager.hasPermissionsRecursiv(form.getSubfolderId(), form.getUser(), "D")) {
				// User hat nicht die Berechtigung zum Löschen
				request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
				
				return DEFAULT_FORWARD;
			} else {
			    Integer parentCatId = form.getParentCategoryId();
				
				VKCCategorySerializer.deleteCategory(form.getUser(), form.getSubfolderId(), !WebShare.isTrashEnabled(), null);

				return new ActionForward("/functionalView.do" +
										 "?functionalViewId=" + form.getFunctionalViewId() +
										 "&subfolderId=" + parentCatId,
										 true);
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}
}