/*
 * $Id: ProjectViewAction.java,v 1.1 2006/10/04 03:14:47 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ProjectViewAction.java,v $
 * Revision 1.1  2006/10/04 03:14:47  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.32  2006/07/12 23:49:34  marbobo
 * + Zurück-Button implementiert
 *
 * Revision 1.31  2006/05/24 17:55:18  marbobo
 * + Toolbar des Html-Editors kann optional angezeigt oder verborgen werden
 *
 * Revision 1.30  2006/05/03 22:18:57  marbobo
 * + Bugfix
 *
 * Revision 1.29  2006/02/27 16:16:14  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.28  2005/09/22 13:18:20  marbobo
 * + Bugfix beim löschen von Kategorien und Dokumenten
 *
 * Revision 1.27  2005/09/01 16:31:31  jonyp
 * changes due to new signature of VKCCategory.deleteCategory/VKCDocument.deleteDocument
 *
 * Revision 1.26  2005/08/26 14:54:29  jonyp
 * changes due to new paramter(user) for deleteDocument
 *
 * Revision 1.25  2005/02/20 17:01:11  marbobo
 * + Beim Speichern der Entities in die Datenbank wird sichergestellt
 *    dass Unicode-Zeichen in Kodierterform (als &#xxxxx;) gespeichert werden
 *
 * Revision 1.24  2004/11/24 09:25:58  lawern
 * Hibernate ist VKC-Geschichte!
 *
 * Revision 1.23  2004/11/10 15:02:49  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.22  2004/10/31 03:04:57  marbobo
 * + Verbesserungen und Bugfixes
 *
 * Revision 1.21  2004/08/20 21:54:16  marbobo
 * + Messages Löschen per Auswahl ( geändert )
 *
 * Revision 1.20  2004/08/07 18:17:05  marbobo
 * + Bugfix für Zeitangaben und Refactorings
 *
 * Revision 1.19  2004/08/04 23:22:54  marbobo
 * + Status auf Flag umgestellt
 *
 * Revision 1.18  2004/07/27 14:55:30  jonyp
 * added new parameter for deletion of categories (definite = true)
 *
 * Revision 1.17  2004/07/20 09:00:51  jonyp
 * added copyright info + cvs log
 *
 *
 */

package vkc.procoba.project;

import java.sql.Connection;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

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.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCCatProjectStep;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCSubCategory;
import vkc.db.helper.DBHelper;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.procoba.project.entities.VKCProject;
import vkc.procoba.project.entities.VKCProjectMessage;
import vkc.procoba.project.entities.VKCProjectSubfolder;
import vkc.security.PermissionManager;
import vkc.util.CategoryUtils;
import vkc.util.DateUtils;
import vkc.util.ProjectUtils;
import vkc.util.StrutsUtils;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;
import vkc.view.bean.NewProjectStepInfo;
import vkc.view.bean.ProjectInfo;

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

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

			if (request.getParameter("action.new.message") != null) {
				return handleNewMessageAction(form);
			} else if (request.getParameter("action.cancel.new.message") != null) {
				return handleCancelNewMessageAction(form);
			} else if (request.getParameter("action.save.new.message") != null) {
				return handleSaveNewMessageAction(form, request);
			} else if (request.getParameter("action.back.to.subfolder") != null) {
				return handleBackToSubfolderAction(form);
            } else if (request.getParameter("action.back.to.parentsubfolder") != null) {
				return handleBackToParentSubfolderAction(form);
            } else if (request.getParameter("action.save.edit.steps") != null) {
				return handleSaveEditStepsAction(form);
			} else if (request.getParameter("action.new.step") != null) {
				return handleNewStepAction(form);
			} else if (request.getParameter("action.delete.steps") != null) {
				return handleDeleteStepsAction(form);
			} else if (request.getParameter("action.change.processid") != null) {
				return handleChangedStepProcessIdsAction(form);
			} else if (request.getParameter("action.change.checkerid") != null) {
				return handleChangedStepCheckerIdsAction(form);
			} else if (request.getParameter("action.delete.document") != null) {
				return handleDeleteDocumentAction(form, request);
			} else if (request.getParameter("action.close.project") != null) {
				return handleCloseProjectAction(form, request);
			} else if (request.getParameter("action.activate.project") != null) {
				return handleActivateProjectAction(form, request);
			} else if (request.getParameter("action.finalize.project") != null) {
				return handleFinalizeProjectAction(form, request);
			} else if (request.getParameter("action.delete.messages") != null) {
				return handleDeleteMessagesAction(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.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.toggle.tinymcetoolbar") != null) {
				return DEFAULT_FORWARD;
			} else {
				return handleInitializeAction(form, request);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

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

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

	protected ActionForward handleHideDocumentDetailsAction(ProjectViewForm form, HttpServletRequest request) {
		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/project/ProjectView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	protected ActionForward handleShowDocumentDetailsAction(ProjectViewForm form, HttpServletRequest request) {
		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/project/ProjectView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	protected ActionForward handleCloseProjectAction(ProjectViewForm form, HttpServletRequest request) throws DBException, ServletException {
		form.setReloadTab(true);
		form.setViewMode(ProjectViewForm.VIEW_MODE_FOLDER);
		closeProjects(form.getProject());
		
	    return handleInitializeAction(form, request);
	}

    private void closeProjects(Object entity) throws DBException {
        List subEntities = new ArrayList();
        
        if (entity instanceof VKCProject) {
            subEntities = ((VKCProject)entity).getSubCategories();
        } else {
            subEntities = ((VKCProjectSubfolder)entity).getSubCategories();
        }
        
        for (int i = 0; i < subEntities.size(); i++) {
            VKCSubCategory s = (VKCSubCategory)subEntities.get(i);
            closeProjects(VKCCategorySerializer.retrieveCategory(s.getSubCategoryId()));
        }

        if (entity instanceof VKCProject) {
            ((VKCProject)entity).setFlag(VKCCategory.FLAG_CLOSED);
    		VKCCategorySerializer.saveCategory((VKCProject)entity);
        } else {
            ((VKCProjectSubfolder)entity).setFlag(VKCCategory.FLAG_CLOSED);
    		VKCCategorySerializer.saveCategory((VKCProjectSubfolder)entity);
        }
    }

    protected ActionForward handleActivateProjectAction(ProjectViewForm form, HttpServletRequest request) throws DBException, ServletException {
		form.setReloadTab(true);
	    form.setViewMode(ProjectViewForm.VIEW_MODE_FOLDER);
		activateProjects(form.getProject());
		
	    return handleInitializeAction(form, request);
	}
	
    private void activateProjects(Object entity) throws DBException {
        List subEntities = new ArrayList();
        
        if (entity instanceof VKCProject) {
            subEntities = ((VKCProject)entity).getSubCategories();
        } else {
            subEntities = ((VKCProjectSubfolder)entity).getSubCategories();
        }
        
        for (int i = 0; i < subEntities.size(); i++) {
            VKCSubCategory s = (VKCSubCategory)subEntities.get(i);
            activateProjects(VKCCategorySerializer.retrieveCategory(s.getSubCategoryId()));
        }

        if (entity instanceof VKCProject) {
            ((VKCProject)entity).setFlag(VKCCategory.FLAG_ACTIVE);
    		VKCCategorySerializer.saveCategory((VKCProject)entity);
        } else {
            ((VKCProjectSubfolder)entity).setFlag(VKCCategory.FLAG_ACTIVE);
    		VKCCategorySerializer.saveCategory((VKCProjectSubfolder)entity);
        }
    }

	protected ActionForward handleFinalizeProjectAction(ProjectViewForm form, HttpServletRequest request) {
		return new ActionForward("/archiveProject.do?projectId=" + form.getProjectId());
	}

	protected ActionForward handleDeleteStepsAction(ProjectViewForm form) {
		List projectStepInfos = form.getProjectStepInfos();
		List selectedProcessedIds = new ArrayList(Arrays.asList(form.getSelectedStepProcessedIds()));
		List selectedCheckedIds = new ArrayList(Arrays.asList(form.getSelectedStepCheckedIds()));
		List selectedEnabledIds = new ArrayList(Arrays.asList(form.getSelectedStepEnabledIds()));
		List changedProcessIds = new ArrayList(Arrays.asList(form.getChangedStepProcessedIds()));
		List changedCheckedIds = new ArrayList(Arrays.asList(form.getChangedStepCheckedIds()));
		Integer[] deleteIds = form.getSelectedStepDeleteIds();

		for (int i = 0; i < deleteIds.length; i++) {
			for (int j = 0; j < projectStepInfos.size(); j++) {
				NewProjectStepInfo s = (NewProjectStepInfo)projectStepInfos.get(j);
				
				if (s.getCatProjStepId().intValue() == deleteIds[i].intValue()) {
					form.removeDynaValue("activityId_" + deleteIds[i]);
					form.removeDynaValue("startdateId_" + deleteIds[i]);
					form.removeDynaValue("enddateId_" + deleteIds[i]);
					selectedProcessedIds.remove(deleteIds[i]);
					selectedCheckedIds.remove(deleteIds[i]);
					selectedEnabledIds.remove(deleteIds[i]);
					changedProcessIds.remove(deleteIds[i]);
					changedCheckedIds.remove(deleteIds[i]);
					projectStepInfos.remove(j);
					break;
				}
			}
		}

		Comparator c = new Comparator() {
			public int compare(Object o1, Object o2) {
				NewProjectStepInfo s1 = (NewProjectStepInfo)o1;
				NewProjectStepInfo s2 = (NewProjectStepInfo)o2;
				return (s1.getStep().intValue() > s2.getStep().intValue()) ? 1 : 0;
			}
		};
		
		Collections.sort(projectStepInfos, c);

		for (int i = 0; i < projectStepInfos.size(); i++) {
			NewProjectStepInfo s = (NewProjectStepInfo)projectStepInfos.get(i);
			s.setStep(new Integer(i+1));
		}

		form.setSelectedStepProcessedIds((Integer[]) selectedProcessedIds.toArray(new Integer[0]));
		form.setSelectedStepCheckedIds((Integer[]) selectedCheckedIds.toArray(new Integer[0]));
		form.setSelectedStepEnabledIds((Integer[]) selectedEnabledIds.toArray(new Integer[0]));
		form.setChangedStepProcessedIds((Integer[]) changedProcessIds.toArray(new Integer[0]));
		form.setChangedStepCheckedIds((Integer[]) changedCheckedIds.toArray(new Integer[0]));
		form.setSelectedStepDeleteIds(new Integer[0]);

		form.setViewMode(ProjectViewForm.VIEW_MODE_EDIT_STEPS);

		return DEFAULT_FORWARD;
	}

	protected ActionForward handleNewStepAction(ProjectViewForm form) {
		Integer stepId = new Integer(form.getSelectedId().intValue());
		List projectStepInfos = form.getProjectStepInfos();

		NewProjectStepInfo step = new NewProjectStepInfo();
		step.setCatProjStepId(new Integer(-form.getUniqueId().intValue()));
		step.setCategoryId(form.getProjectId());
		step.setStep(stepId);
		step.setSelected(false);
		step.setEnabled(true);
		step.setStartDate("");
		step.setEndDate("");
		step.setActivity("");
				
		step.setProcessorId(null);
		step.setProcessedTS("");

		step.setCheckerId(null);
		step.setCheckedTS("");
		
		for (int i = 0; i < projectStepInfos.size(); i++) {
			NewProjectStepInfo s = (NewProjectStepInfo)projectStepInfos.get(i);
			
			if (s.getStep().intValue() >= stepId.intValue()) {
				s.setStep(new Integer(s.getStep().intValue() + 1));
			}
		}

		form.setDynaValue("activityId_" + step.getCatProjStepId().toString(), step.getActivity());
		form.setDynaValue("startdateId_" + step.getCatProjStepId().toString(), step.getStartDate());
		form.setDynaValue("enddateId_" + step.getCatProjStepId().toString(), step.getEndDate());

		List selectedEnabledIds = new ArrayList(Arrays.asList(form.getSelectedStepEnabledIds()));
		selectedEnabledIds.add(step.getCatProjStepId());
	
		projectStepInfos.add(step);
	
		form.setSelectedStepEnabledIds((Integer[])selectedEnabledIds.toArray(new Integer[0]));
		
		form.setUniqueId(new Integer(form.getUniqueId().intValue() + 1));
		
		form.setViewMode(ProjectViewForm.VIEW_MODE_EDIT_STEPS);

		return DEFAULT_FORWARD;
	}

	protected ActionForward handleChangedStepCheckerIdsAction(ProjectViewForm form) {
		Integer id = new Integer(form.getSelectedId().intValue());
		List ids = new ArrayList();
		ids.addAll(Arrays.asList(form.getChangedStepCheckedIds()));
		
		if (!ids.contains(id)) {
			ids.add(id);
		}
		
		Integer[] checkedIds = (Integer[])ids.toArray(new Integer[0]);
		form.setChangedStepCheckedIds(checkedIds);
		form.setViewMode(ProjectViewForm.VIEW_MODE_EDIT_STEPS);

		return DEFAULT_FORWARD;
	}

	protected ActionForward handleChangedStepProcessIdsAction(ProjectViewForm form) {
		Integer id = new Integer(form.getSelectedId().intValue());
		ArrayList ids = new ArrayList();
		ids.addAll(Arrays.asList(form.getChangedStepProcessedIds()));
		
		if (!ids.contains(id)) {
			ids.add(id);
		}
		
		Integer[] processedIds = (Integer[])ids.toArray(new Integer[0]);
		form.setChangedStepProcessedIds(processedIds);
		form.setViewMode(ProjectViewForm.VIEW_MODE_EDIT_STEPS);

		return DEFAULT_FORWARD;
	}

	/**
	 * Methode löscht ein Dokument aus dem aktuell ausgewählten Projektordner
	 */
	protected ActionForward handleDeleteDocumentAction(ProjectViewForm form, HttpServletRequest request) throws ServletException {
		try {
			if (!PermissionManager.hasPermission(form.getSubfolder().getAcl(), form.getUser(), 'd')) {
				StrutsUtils.addInfoMessage(request, "project.info.delete.doc.denied");
				
				return DEFAULT_FORWARD;
			}

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

			return DEFAULT_FORWARD;
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}

	/**
	 * Methode führt die Initialisierung des Forms durch
	 */
	protected ActionForward handleInitializeAction(ProjectViewForm form, HttpServletRequest request) throws ServletException {
		try {
			if (request.getParameter("sysLinkMessageKey") != null) {
				request.setAttribute(WebShare.INFO_KEY, request.getParameter("sysLinkMessageKey"));
			}
			
			if (form.getProject() == null) {
				// kein Projekt ausgewählt
				List projectInfos = form.getUser().getProjectInfos();
				
				if (projectInfos.size() > 0) {
					ProjectInfo info = (ProjectInfo)projectInfos.get(0);
					form.setProjectId(info.getId());
					form.setSubfolderId(info.getId());
					
					if (!form.getUserIsMember()) {
						// angemeldeter Benutzer hat keine Leserechte
						StrutsUtils.addErrorMessage(request, "project.error.access.denied");
					}
					
					return DEFAULT_FORWARD;
				} 

				StrutsUtils.addErrorMessage(request, "project.info.no.projects");
				
				return DEFAULT_FORWARD;
			} else if (!form.getUserIsMember()) {
				// angemeldeter Benutzer hat keine Leserechte
				StrutsUtils.addErrorMessage(request, "project.error.access.denied");
				
				return DEFAULT_FORWARD;
			} else if (!form.getProject().isProjectCategory()) {
				// Kategorie ist kein Projektordner
				StrutsUtils.addErrorMessage(request, "project.error.not.project.category");
				
				return DEFAULT_FORWARD;
			}

			if (form.getViewMode().equals(ProjectViewForm.VIEW_MODE_EDIT_STEPS)) {
				synchronizeProjectSteps(form);
			}

			if (form.getSubfolderId() == null) {
				form.setSubfolderId(form.getProjectId());
			}

			return DEFAULT_FORWARD;
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}

	protected ActionForward handleSaveEditStepsAction(ProjectViewForm form) throws DBException {
		List projectSteps = form.getProjectSteps();
		List selectedProcessedIds = new ArrayList(Arrays.asList(form.getSelectedStepProcessedIds()));
		List selectedCheckedIds = new ArrayList(Arrays.asList(form.getSelectedStepCheckedIds()));
		List selectedEnabledIds = new ArrayList(Arrays.asList(form.getSelectedStepEnabledIds()));
		List changedProcessIds = new ArrayList(Arrays.asList(form.getChangedStepProcessedIds()));
		List changedCheckedIds = new ArrayList(Arrays.asList(form.getChangedStepCheckedIds()));

		if (!form.getUserIsLeader() && form.getUserHasWritePermission()) {
			for (int i = 0; i < projectSteps.size(); i++) {
				VKCCatProjectStep step = (VKCCatProjectStep)projectSteps.get(i);

				if (selectedProcessedIds.contains(step.getCatProjStepId())) {
					if (step.isEnabled() && !step.isProcessed()) {
						step.setProcessorId(form.getUser().getUserId());
						step.setProcessedTS(new Timestamp(System.currentTimeMillis()));
					}
				}
			}
		} else if (form.getUserIsLeader()) {
			for (int i = 0; i < projectSteps.size(); i++) {
				VKCCatProjectStep step = (VKCCatProjectStep)projectSteps.get(i);
				String activity = (String)form.getDynaValue("activityId_" + step.getCatProjStepId());
				String startdate = (String)form.getDynaValue("startdateId_" + step.getCatProjStepId());
				String enddate = (String)form.getDynaValue("enddateId_" + step.getCatProjStepId());
				step.setActivity(activity);
				step.setStartDate(new Timestamp(DateUtils.parseDate(startdate).getTime()));
				Calendar c = Calendar.getInstance();
				c.setTime(DateUtils.parseDate(enddate));
				c.set(Calendar.HOUR_OF_DAY, 23);
				c.set(Calendar.MINUTE, 59);
				c.set(Calendar.SECOND, 59);
				step.setEndDate(new Timestamp(c.getTimeInMillis()));

				if (selectedProcessedIds.contains(step.getCatProjStepId())) {
					if (changedProcessIds.contains(step.getCatProjStepId())) {
						step.setProcessorId(form.getUser().getUserId());
						step.setProcessedTS(new Timestamp(System.currentTimeMillis()));
					}
				} else if (changedProcessIds.contains(step.getCatProjStepId())) {
					step.setProcessorId(null);
					step.setProcessedTS(null);
				}

				if (selectedCheckedIds.contains(step.getCatProjStepId())) {
					if (changedCheckedIds.contains(step.getCatProjStepId())) {
						step.setCheckerId(form.getUser().getUserId());
						step.setCheckedTS(new Timestamp(System.currentTimeMillis()));
					}
				} else if (changedCheckedIds.contains(step.getCatProjStepId())) {
					step.setCheckerId(null);
					step.setCheckedTS(null);
				}

				if (selectedEnabledIds.contains(step.getCatProjStepId())) {
					step.setEnabled(true);
				} else {
					step.setEnabled(false);
				}
			}

		}
		
		form.getProject().setProjectSteps(projectSteps);
		VKCCategorySerializer.saveCategory(form.getProject());
		form.reloadProject();
		synchronizeProjectSteps(form);

		form.setViewMode(ProjectViewForm.VIEW_MODE_EDIT_STEPS);
		
		return DEFAULT_FORWARD;
	}

	protected void synchronizeProjectSteps(ProjectViewForm form) throws DBException {
		//Projektschritte setzen
		if (!form.getProject().getProjectSteps().isEmpty()) {
			List processedIds = new ArrayList();
			List checkedIds = new ArrayList();
			List enabledIds = new ArrayList();
			
			form.getProjectStepInfos().clear();
			
			for (int i = 0; i < form.getProject().getProjectSteps().size(); i++) {
				VKCCatProjectStep step = (VKCCatProjectStep)form.getProject().getProjectSteps().get(i);

				form.setDynaValue("activityId_" + step.getCatProjStepId().toString(), step.getActivity());
				form.setDynaValue("startdateId_" + step.getCatProjStepId().toString(), step.getStartDateString());
				form.setDynaValue("enddateId_" + step.getCatProjStepId().toString(), step.getEndDateString());

				if (step.isProcessed()) {
					processedIds.add(step.getCatProjStepId());
				}

				if (step.isChecked()) {
					checkedIds.add(step.getCatProjStepId());
				}

				if (step.isEnabled()) {
					enabledIds.add(step.getCatProjStepId());
				}
				
				form.getProjectStepInfos().add(step.toNewProjectStepInfo());
			}

			form.setSelectedStepProcessedIds((Integer[]) processedIds.toArray(new Integer[0]));
			form.setSelectedStepCheckedIds((Integer[]) checkedIds.toArray(new Integer[0]));
			form.setSelectedStepEnabledIds((Integer[]) enabledIds.toArray(new Integer[0]));
			form.setChangedStepProcessedIds(new Integer[0]);
			form.setChangedStepCheckedIds(new Integer[0]);
		}
	}

	protected ActionForward handleBackToSubfolderAction(ProjectViewForm form) {
		return new ActionForward("/projectView.do" +
		        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_FOLDER +
		        				 "&projectId=" + form.getProjectId() +
		        				 "&subfolderId=" + form.getSubfolderId(),
		        				 true);
	}

	protected ActionForward handleBackToParentSubfolderAction(ProjectViewForm form) throws DBException {
		return new ActionForward("/projectView.do" +
		        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_FOLDER +
		        				 "&projectId=" + form.getProjectId() +
		        				 "&subfolderId=" + form.getSubfolder().getParentCategoryId(),
		        				 true);
	}

	protected ActionForward handleNewMessageAction(ProjectViewForm form) {
		form.setViewMode(ProjectViewForm.VIEW_MODE_NEW_MESSAGE);
		
		return DEFAULT_FORWARD;
	}

	protected ActionForward handleCancelNewMessageAction(ProjectViewForm form) {
		return new ActionForward("/projectView.do" +
		        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_MESSAGES +
		        				 "&projectId=" + form.getProjectId() +
		        				 "&subfolderId=" + form.getSubfolderId(),
		        				 true);
	}

	protected ActionForward handleSaveNewMessageAction(ProjectViewForm form, HttpServletRequest request) throws ServletException {
		Connection conn = null;

		try {
			conn = WebShare.database.getConnection();

			Integer projectId = form.getProjectId();
			Integer creatorId = form.getUser().getUserId();
			Set recepientIds = CategoryUtils.getUserIdsWithReadAccess(form.getProject(), conn);

			for (Iterator iter = recepientIds.iterator(); iter.hasNext();) {
				Integer recepientId = (Integer)iter.next();
/*
				if ( creatorId.intValue() == recepientId.intValue() ) {
					continue;
				}
*/
				VKCProjectMessage msg = new VKCProjectMessage();
				msg.setProjectId(projectId);
				msg.setCreatorId(creatorId);
				msg.setCreationDate(new Date());
				
				String newMessage = VKCStringUtils.filterUnicodeChars(form.getNewMessage());
				
				if (!form.isTinyMCECompatible()) {
					newMessage = VKCStringUtils.decodeXmlEntities(newMessage);
					newMessage = VKCStringUtils.encodeNamedXmlEntities(newMessage);
				}
				
				msg.setText(newMessage);
				msg.setRecepientId(recepientId);

				ProjectUtils.saveProjectMessage(msg, conn);
			}

			conn.commit();

			StrutsUtils.addInfoMessage(request, "project.info.message.send");
			
			return new ActionForward("/projectView.do" +
			        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_MESSAGES +
			        				 "&projectId=" + form.getProjectId() +
			        				 "&subfolderId=" + form.getSubfolderId(),
			        				 true);
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		} finally {
			DBHelper.close(conn);
		}
	}

	/**
	 * Methode löscht ein Dokument aus dem aktuell ausgewählten Projektordner
	 */
	protected ActionForward handleDeleteMessagesAction(ProjectViewForm form, HttpServletRequest request) throws ServletException {
		try {
			Integer[] ids = form.getSelectedIds();
			
			for (int i = 0; i < ids.length; i++) {
			    ProjectUtils.deleteProjectMessage(ids[i]);
			}
			
			return new ActionForward("/projectView.do" +
			        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_MESSAGES +
			        				 "&projectId=" + form.getProjectId() +
			        				 "&subfolderId=" + form.getSubfolderId(),
			        				 true);
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}
	
	/**
	 * Methode löscht ein Subfolder
	 */
	protected ActionForward handleDeleteSubfolder(ProjectViewForm form, HttpServletRequest request) throws ServletException {
		try {
			if (form.isProjectRoot()) {
				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.getSubfolder().getParentCategoryId();
				
				VKCCategorySerializer.deleteCategory(form.getUser(), form.getSubfolderId(), !WebShare.isTrashEnabled(), null);

				return new ActionForward("/projectView.do" +
				        				 "?viewMode=" + ProjectViewForm.VIEW_MODE_FOLDER +
				        				 "&projectId=" + form.getProjectId() +
				        				 "&subfolderId=" + parentCatId,
				        				 true);
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}
}