/*
 * $Id: CreateProjectAction.java,v 1.1 2006/10/04 03:14:46 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * $Log: CreateProjectAction.java,v $
 * Revision 1.1  2006/10/04 03:14:46  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.13  2006/05/24 17:55:19  marbobo
 * + Toolbar des Html-Editors kann optional angezeigt oder verborgen werden
 *
 * Revision 1.12  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.11  2005/02/14 14:01:48  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.10  2004/11/10 15:02:49  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.9  2004/11/02 21:42:30  marbobo
 * + Einige Funktionen für Gast-Benutzer gesperrt
 * + WebShare.LOGIN_PAGE mit WebShare.getLoginPage() ersetzt
 *
 * Revision 1.8  2004/07/20 09:00:52  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.procoba.project;

import java.util.Iterator;

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.util.ProjectUtils;
import vkc.util.VKCStringUtils;
import vkc.view.PageId;
import vkc.view.WebShare;
import vkc.view.bean.NewProjectStepInfo;
import vkc.db.entities.VKCAclType;
import vkc.db.entities.VKCCategory;
import vkc.db.serializer.VKCAclSerializer;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.exception.AclException;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.procoba.project.entities.VKCProject;
import vkc.security.PermissionManager;
import vkc.security.VKCAcl;

/**
 * DOCUMENT ME!!!
 *
 * @author vchris
 */
public class CreateProjectAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/procoba/project/CreateProjectTemplate.jsp");

	private ActionForward INFO_FORWARD = new ActionForward("/templates/${template.name}/common/InfoPage.jsp");

	public ActionForward execute(ActionMapping mapping, 
	        					 ActionForm f, 
	        					 HttpServletRequest request, 
	        					 HttpServletResponse response)
	throws ServletException	{
		try {
			// Prüfen, ob Projektmanagement aktiviert ist
			if (!VKCSysParameterSerializer.isProjectManagementEnabled()) {
				request.setAttribute(WebShare.INFO_KEY, "vkc.info.projectmanagement_disabled");

				return INFO_FORWARD;
			}

			CreateProjectForm form = (CreateProjectForm) f;

			if (request.getParameter("action.new.step") != null) {
				return handleNewStepAction(form, request);
			} else if (request.getParameter("action.create") != null) {
				return handleCreateAction(form, request);
			} else if (request.getParameter("action.cancel") != null) {
				return handleCancelAction(form, request);
			} else if (request.getParameter("action.delete.steps") != null) {
				return handleDeleteStepAction(form, request);
			} else if (request.getParameter("action.toggle.tinymcetoolbar") != null) {
				return DEFAULT_FORWARD;
			} else {
				return handleInitializeAction(form, request);
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e);
		}
	}

	private ActionForward handleNewStepAction(CreateProjectForm form, HttpServletRequest request) {
		NewProjectStepInfo step = new NewProjectStepInfo();
		form.getProjectSteps().add(step);

		return DEFAULT_FORWARD;
	}

	private ActionForward handleDeleteStepAction(CreateProjectForm form, HttpServletRequest request) {
		for (Iterator iter = form.getProjectSteps().iterator(); iter.hasNext();) {
			NewProjectStepInfo step = (NewProjectStepInfo) iter.next();

			if (step.isSelected()) {
				iter.remove();
			}
		}

		return DEFAULT_FORWARD;
	}

	private ActionForward handleCancelAction(CreateProjectForm form, HttpServletRequest request) {
		String forwardURL = "";

		if (form.getSourcePageId().equals(PageId.PROJECT_VIEW)) {
			Integer projectManagementRootId = WebShare.getCategorySettings().getProjectManagementRootId();

			if (form.getParentCategoryId().equals(projectManagementRootId)) {
				forwardURL = "/projectView.do?viewMode="
						+ ProjectViewForm.VIEW_MODE_FOLDER + "&projectId="
						+ form.getProjectId() + "&subfolderId="
						+ form.getProjectId();
			} else {
				forwardURL = "/projectView.do?viewMode="
						+ ProjectViewForm.VIEW_MODE_FOLDER + "&projectId="
						+ form.getTargetId() + "&subfolderId="
						+ form.getSubTargetId();
			}

			return new ActionForward(forwardURL, true);
		} else if (form.getSourcePageId().equals(PageId.FUNCTIONAL_VIEW)) {
			Integer projectManagementRootId = WebShare.getCategorySettings().getProjectManagementRootId();

			if (form.getParentCategoryId().equals(projectManagementRootId)) {
				forwardURL = "/projectView.do?viewMode="
						+ ProjectViewForm.VIEW_MODE_FOLDER + "&projectId="
						+ form.getProjectId() + "&subfolderId="
						+ form.getProjectId();
			} else {
				forwardURL = "/functionalView.do?functionalViewId="
						+ form.getTargetId() + "&subfolderId="
						+ form.getSubTargetId();
			}

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

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

	private ActionForward handleInitializeAction(CreateProjectForm form, HttpServletRequest request) {
		return DEFAULT_FORWARD;
	}

	private ActionForward handleCreateAction(CreateProjectForm form, HttpServletRequest request) throws DBException, AclException {
		Integer templateId = form.getTemplateIdSelect();

		// Überprüfen, ob der Benutzer die Berechtigung hat
		VKCCategory targetCategory = VKCCategorySerializer.retrieveCategory(form.getParentCategoryId());
		
		if (form.getUser().isGuestUser() 
		  || !PermissionManager.hasPermission(targetCategory.getAcl(), form.getUser(), 'C')) {
			request.setAttribute(WebShare.INFO_KEY, "category.create.denied");
			
			return INFO_FORWARD;
		}

		if (templateId != null && templateId.intValue() > 0) {
			VKCAcl acl = null;

			if (CreateProjectForm.PERMISSIONS_COPY_FROM_DEFAULT.equals(form.getPermissionsSettings())) {
				// Default ACL der Zielkategorie für das neue Projekt übernehmen
				acl = VKCAclSerializer.getDefaultCatAcl(form.getUser(), targetCategory, true);
			} else if (CreateProjectForm.PERMISSIONS_COPY_FROM_TARGET.equals(form.getPermissionsSettings())) {
				// ACL der Zielkategorie für das neue Projekt übernehmen
				acl = VKCAclSerializer.getAclByCategoryId(targetCategory.getCategoryId());
			} else if (CreateProjectForm.PERMISSIONS_COPY_FROM_TEMPLATE.equals(form.getPermissionsSettings())) {
				// ACL der Vorlagenkategorie übernehmen
				acl = VKCAclSerializer.getAclByCategoryId(templateId);
			}

			
			String description = VKCStringUtils.filterUnicodeChars(form.getDescription());
			
			if (!form.isTinyMCECompatible()) {
				description = VKCStringUtils.decodeXmlEntities(description);
				description = VKCStringUtils.encodeNamedXmlEntities(description);
			}
			
			Integer projectId = ProjectUtils.createProjectByTemplate(VKCStringUtils.filterUnicodeChars(form.getName()),
			        												 VKCStringUtils.filterUnicodeChars(form.getKeywords()),
			        												 description, 
												   					 form.getCatProjectSteps(),
												   					 targetCategory.getCategoryId(),
												   					 templateId,
												   					 acl,
												   					 form.getUser());
			
			VKCCategory category = VKCCategorySerializer.retrieveCategory(projectId);
			PermissionManager.setCategoriesOwnerPermissions(category, new Integer(VKCAclType.USER_TYPE), form.getUser().getUserId(), form.getUser().getUserId());
			form.setProjectId(projectId);
		} else {
			VKCProject projectCategory = new VKCProject();
			projectCategory.setParentCategoryId(targetCategory.getCategoryId());
			VKCAcl newAcl = null;
			
			if (CreateProjectForm.PERMISSIONS_COPY_FROM_TARGET.equals(form.getPermissionsSettings())) {
				newAcl = VKCAclSerializer.getAclByCategoryId(targetCategory.getCategoryId());
			} else {
				newAcl = VKCAclSerializer.getDefaultCatAcl(form.getUser(), targetCategory, true);
			}

			PermissionManager.setCategoryOwnerPermissions(new Integer(VKCAclType.USER_TYPE), form.getUser().getUserId(), form.getUser().getUserId(), newAcl);
			newAcl.setAclId(null);
			projectCategory.setAcl(newAcl);
			projectCategory.setName(VKCStringUtils.filterUnicodeChars(form.getName()));
			
			String description = VKCStringUtils.filterUnicodeChars(form.getDescription());
			
			if (!form.isTinyMCECompatible()) {
				description = VKCStringUtils.decodeXmlEntities(description);
				description = VKCStringUtils.encodeNamedXmlEntities(description);
			}
			
			projectCategory.setDescription(description);
			projectCategory.setKeywordsByString(VKCStringUtils.filterUnicodeChars(form.getKeywords()));
			projectCategory.setProjectSteps(form.getCatProjectSteps());

            VKCCategorySerializer.saveCategory(projectCategory);
			form.setProjectId(projectCategory.getCategoryId());
		}

		return handleCancelAction(form, request);
	}
}