/*
 * $Id: CreateCategoryAction.java,v 1.59 2006/10/04 03:14:33 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: CreateCategoryAction.java,v $
 * Revision 1.59  2006/10/04 03:14:33  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.58  2006/08/24 14:51:23  marbobo
 * + Bugfix
 *
 * Revision 1.57  2006/05/24 17:57:50  marbobo
 * + Toolbar des Html-Editors kann optional angezeigt oder verborgen werden
 *
 * Revision 1.56  2006/02/27 16:15:59  marbobo
 * + Systemsichten hinzugefügt
 * + SysLinks angepasst
 * + Benutzer können falls gewünscht Dokumentqueries anlegen
 *
 * Revision 1.55  2005/02/20 16:59:11  marbobo
 * + Beim Speichern der Entities in die Datenbank wird sichergestellt
 *    dass Unicode-Zeichen in Kodierterform (als &#xxxxx;) gespeichert werden
 *
 * Revision 1.54  2005/02/14 14:01:51  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.53  2005/02/10 16:28:18  bigmac
 * Forwards angepasst
 *
 * Revision 1.52  2005/02/03 23:27:46  marbobo
 * + Kalendar-Action hinzugefügt
 *
 * Revision 1.51  2004/11/02 21:42:30  marbobo
 * + Einige Funktionen für Gast-Benutzer gesperrt
 * + WebShare.LOGIN_PAGE mit WebShare.getLoginPage() ersetzt
 *
 * Revision 1.50  2004/10/19 19:58:40  marbobo
 * + Globale Kategorie-Attribute und Dyn. Attribute überarbeitet
 *
 * Revision 1.49  2004/10/06 12:33:38  marbobo
 * + Suche nach Globalen Dokument-Attributen korrigiert
 *
 * Revision 1.48  2004/10/05 17:59:50  marbobo
 * + Suche nach Globalen Dokument-Attributen überarbeitet
 *
 * Revision 1.47  2004/09/03 00:42:43  marbobo
 * + Kategorieauswahl über ein Explorer für die Suche eingebaut
 *
 * Revision 1.46  2004/08/09 13:45:42  marbobo
 * + Preview für Defaultcategory-Acls
 *
 * Revision 1.45  2004/07/20 08:48:48  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.view.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

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 org.apache.struts.util.LabelValueBean;

import vkc.db.entities.VKCAclType;
import vkc.db.entities.VKCAddAttribute;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCDynaAttribute;
import vkc.db.entities.VKCSearchQuery;
import vkc.db.serializer.VKCAclSerializer;
import vkc.db.serializer.VKCAddAttributeSerializer;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.exception.AclException;
import vkc.exception.DBException;
import vkc.procoba.project.ProjectViewForm;
import vkc.procoba.project.entities.VKCProject;
import vkc.procoba.project.entities.VKCProjectSubfolder;
import vkc.security.PermissionManager;
import vkc.security.VKCAcl;
import vkc.util.VKCStringUtils;
import vkc.view.PageId;
import vkc.view.WebShare;
import vkc.view.form.CreateCategoryForm;

public final class CreateCategoryAction extends Action {
	private ActionForward DEFAULT_FORWARD =	new ActionForward("/templates/${template.name}/admin/CreateCategoryTemplate.jsp");
	private ActionForward DEFAULT_FORWARD_ANCHORDYNAATTRIBUTES = new ActionForward("/templates/${template.name}/admin/CreateCategoryTemplate.jsp?anchor=dynaattributes");

    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 {
            CreateCategoryForm form = (CreateCategoryForm) f;

            if (form.getUser().isGuestUser()
               || !PermissionManager.hasPermission(form.getParentCategory().getAcl(), form.getUser(), 'C')) {
                request.setAttribute(WebShare.INFO_KEY, "category.create.denied");
                
                return INFO_FORWARD;
            }

            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.edit.searchquery") != null) {
				return handleEditSearchQueryAction(form);
			} else if (request.getParameter("action.change.category") != null) {
			    return handleChangeCategoryAction(form, request);
			} else if (request.getParameter("action.save.searchquery") != null) {
				return handleSaveSearchQueryAction(form);
			} else if (request.getParameter("action.back.searchquery") != null) {
				form.setQuery(new VKCSearchQuery());
				form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);
				
				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.delete.searchquery") != null) {
				form.setSearchQuery("");
				form.setQuery(new VKCSearchQuery());
				form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);
				
				return DEFAULT_FORWARD;
			} else if (request.getParameter("btn_query.validFrom.x") != null
			         || request.getParameter("btn_query.validUntil.x") != null) {
				form.setEditMode(CreateCategoryForm.EDITMODE_SEARCHQUERY);
				
				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.toggle.tinymcetoolbar") != null) {
				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.add.dynaattribute") != null) {
                return handleAddDynAttributeAction(form, request);
            } else if (request.getParameter("action.delete.dynaattribute.x") != null) {
                return handleDeleteDynAttributeAction(form, request);
	        } else {
	            return handleInitializeAction(form, request);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

	private ActionForward handleInitializeAction(CreateCategoryForm form, HttpServletRequest request) throws DBException {
		Integer rootId = WebShare.getCategorySettings().getProjectManagementRootId();
		
		if (form.getParentCategory().getCategoryId().equals(rootId)) {
			// In der Wurzelkategorie für Projekte können nur Projekte angelegt werden
			return handleCreateProjectAction(form, request);
		}
		
        List addCatAttributes = VKCAddAttributeSerializer.getAllAddCatAttributes();
        
        for (int i = 0; i < addCatAttributes.size(); i++) {
            VKCAddAttribute attr = (VKCAddAttribute)addCatAttributes.get(i);
            form.getAddCatAttributes().put("addcatattrId_" + attr.getAttrId(), attr.getDefaultValue());
        }

        form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);
	    
	    return DEFAULT_FORWARD;
	}
	
	private ActionForward handleCreateProjectAction(CreateCategoryForm form, HttpServletRequest request) {
		Integer targetId = form.getTargetId();
		Integer subTargetId = form.getSubTargetId();

		if (targetId != null && subTargetId != null) {
			return new ActionForward("/createProject.do?parentCategoryId=" + form.getParentCategoryId() +
									 "&sourcePageId=" + form.getSourcePageId() +
									 "&targetId=" + targetId +
									 "&subTargetId=" + subTargetId +
									 "&validate=false" +
									 "&copyParentAcl=true", true);
		}

		if (targetId != null && subTargetId == null) {
			return new ActionForward("/createProject.do?parentCategoryId=" + form.getParentCategoryId() +
									 "&sourcePageId=" + form.getSourcePageId() +
									 "&targetId=" + targetId +
									 "&validate=false" +
									 "&copyParentAcl=true", true);
		}

		if (targetId == null && subTargetId != null) {
			return new ActionForward("/createProject.do?parentCategoryId=" + form.getParentCategoryId() +
									 "&sourcePageId=" + form.getSourcePageId() +
									 "&subTargetId=" + subTargetId +
									 "&validate=false" +
									 "&copyParentAcl=true", true);
		}

		return new ActionForward("/createProject.do?parentCategoryId=" + form.getParentCategoryId() +
								 "&sourcePageId=" + form.getSourcePageId() +
								 "&validate=false" +
								 "&copyParentAcl=true", true);
	}

	private ActionForward handleCreateAction(CreateCategoryForm form, HttpServletRequest request) throws DBException, AclException {
		VKCCategory parentCategory = form.getParentCategory();
		VKCCategory newCategory = new VKCCategory();

		if (parentCategory.isProjectCategory()) {
			VKCProject project = (VKCProject)parentCategory;

			VKCProjectSubfolder newSubfolder = new VKCProjectSubfolder();
			newSubfolder.setParentCategoryId(project.getCategoryId());
			newSubfolder.setProjectId(project.getCategoryId());

			newCategory = newSubfolder;
		} else if (parentCategory.isProjectSubfolder()) {
			VKCProjectSubfolder subfolder = (VKCProjectSubfolder)parentCategory;

			VKCProjectSubfolder newSubfolder = new VKCProjectSubfolder();
			newSubfolder.setParentCategoryId(subfolder.getCategoryId());
			newSubfolder.setProjectId(subfolder.getProjectId());

			newCategory = newSubfolder;
		}

		newCategory.setName(VKCStringUtils.filterUnicodeChars(form.getName()));
		newCategory.setKeywordsByString(VKCStringUtils.filterUnicodeChars(form.getKeywords()));
		
		String description = VKCStringUtils.filterUnicodeChars(form.getDescription());
		
		if (!form.isTinyMCECompatible()) {
			description = VKCStringUtils.decodeXmlEntities(description);
			description = VKCStringUtils.encodeNamedXmlEntities(description);
		}
		
		newCategory.setDescription(description);
		newCategory.setParentCategoryId(form.getParentCategoryId());
		newCategory.setCreatorId(form.getUser().getUserId());

        Iterator it = form.getAllAddCatAttributes().keySet().iterator();
        
        while (it.hasNext()) {
            String key = (String)it.next();
            VKCAddAttribute attr = (VKCAddAttribute)form.getAllAddCatAttributes().get(key);
            attr.setValuestring(VKCStringUtils.filterUnicodeChars((String)form.getAddCatAttributeValue(key)));
        }
        
        newCategory.setAddAttributes(new Vector(form.getAllAddCatAttributes().values()));

        List dynaAttributes = new ArrayList();
        
        for (int i = 0; i < form.getDynaAttributes().size(); i++) {
            LabelValueBean bean = (LabelValueBean)form.getDynaAttributes().get(i);
            VKCDynaAttribute dynaAttr = new VKCDynaAttribute();
            dynaAttr.setName(VKCStringUtils.filterUnicodeChars(bean.getLabel()));
            dynaAttr.setValue(VKCStringUtils.filterUnicodeChars(bean.getValue()));
            dynaAttributes.add(dynaAttr);
        }
		
        newCategory.setDynaAttributes(dynaAttributes);

		VKCAcl acl = null;
		
		if (form.getPermissionsSettings().equals(CreateCategoryForm.PERMISSIONS_COPY_FROM_PARENT)) {
		    acl = VKCAclSerializer.getAclByCategoryId(form.getParentCategoryId());
		} else if (form.getPermissionsSettings().equals(CreateCategoryForm.PERMISSIONS_COPY_FROM_DEFAULT)) {
		    acl = VKCAclSerializer.getDefaultCatAcl(form.getUser(), parentCategory, true);
		} else {
		    acl = VKCAclSerializer.getDefaultCatAcl(form.getUser(), parentCategory, true);
		}
		
		PermissionManager.setCategoryOwnerPermissions(new Integer(VKCAclType.USER_TYPE), form.getUser().getUserId(), form.getUser().getUserId(), acl);
		acl.setAclId(null);
		newCategory.setAcl(acl);

		VKCCategorySerializer.saveCategory(newCategory);

		if (form.isHasPermissionForSearchQueries()) {
			VKCSearchQuery query = new VKCSearchQuery();
			query.setQuery(form.getSearchQuery());
			VKCCategorySerializer.saveSearchQuery(query, newCategory.getCategoryId());
		}

		String forwardURL = "";

		if (form.getSourcePageId().equals(PageId.PROJECT_VIEW)) {
			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)) {
			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 handleCancelAction(CreateCategoryForm 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();
			
			return new ActionForward(forwardURL, true);
		} else if (form.getSourcePageId().equals(PageId.FUNCTIONAL_VIEW)) {
			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();
			}

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

	private ActionForward handleSaveSearchQueryAction(CreateCategoryForm form) {
		form.setSearchQuery(form.getQuery().getQuery());
		form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleEditSearchQueryAction(CreateCategoryForm form) {
		VKCSearchQuery query = new VKCSearchQuery();
		query.setQuery(form.getSearchQuery());
		form.setQuery(query);
		form.setEditMode(CreateCategoryForm.EDITMODE_SEARCHQUERY);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleChangeCategoryAction(CreateCategoryForm form, HttpServletRequest request) {
		form.getQuery().setSelectedCategoryId(request.getParameter("selectedCategoryId"));
		form.setEditMode(CreateCategoryForm.EDITMODE_SEARCHQUERY);

		return DEFAULT_FORWARD;
	}

    private ActionForward handleAddDynAttributeAction(CreateCategoryForm form, HttpServletRequest request) {
        form.getDynaAttributes().add(new LabelValueBean("", ""));
		form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);
        
        return DEFAULT_FORWARD_ANCHORDYNAATTRIBUTES;
    }

    private ActionForward handleDeleteDynAttributeAction(CreateCategoryForm form, HttpServletRequest request) {
        int index = form.getSelectedIndex().intValue();

        if (index >= 0 && index < form.getDynaAttributes().size()) {
            form.getDynaAttributes().remove(index);
        }
        
		form.setEditMode(CreateCategoryForm.EDITMODE_CATEGORY);

		return DEFAULT_FORWARD_ANCHORDYNAATTRIBUTES;
    }
}