/*
 * $Id: EditCategoryAction.java,v 1.60 2006/10/04 03:14:32 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: EditCategoryAction.java,v $
 * Revision 1.60  2006/10/04 03:14:32  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.59  2006/05/31 14:55:01  marbobo
 * + Bugfix
 *
 * Revision 1.58  2006/05/31 14:00:32  marbobo
 * + Zeilenumbrüche bei Beschreibungsfelder anzeigen
 *
 * 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:16:04  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:52  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/10 15:02:45  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.50  2004/11/02 21:42:30  marbobo
 * + Einige Funktionen für Gast-Benutzer gesperrt
 * + WebShare.LOGIN_PAGE mit WebShare.getLoginPage() ersetzt
 *
 * Revision 1.49  2004/10/19 19:58:40  marbobo
 * + Globale Kategorie-Attribute und Dyn. Attribute überarbeitet
 *
 * Revision 1.48  2004/10/06 12:33:38  marbobo
 * + Suche nach Globalen Dokument-Attributen korrigiert
 *
 * Revision 1.47  2004/10/05 17:59:50  marbobo
 * + Suche nach Globalen Dokument-Attributen überarbeitet
 *
 * Revision 1.46  2004/09/03 00:42:43  marbobo
 * + Kategorieauswahl über ein Explorer für die Suche eingebaut
 *
 * Revision 1.45  2004/06/27 17:36:01  marbobo
 * + Quellcode maintenance
 *
 * Revision 1.44  2004/05/25 21:08:52  marbobo
 * + getTargetId() setTargetId() getSubTargetId() setSubTargetId()
 *
 * Revision 1.43  2004/04/27 15:10:25  jonyp
 * added few lines of code to add new permissions (a/q)
 *
 */
package vkc.view.action;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.BadLocationException;

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.VKCAddAttribute;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCDynaAttribute;
import vkc.db.entities.VKCSearchQuery;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.procoba.project.ProjectViewForm;
import vkc.procoba.project.entities.VKCProject;
import vkc.security.PermissionManager;
import vkc.util.VKCStringUtils;
import vkc.view.PageId;
import vkc.view.WebShare;
import vkc.view.form.BasicActionForm;
import vkc.view.form.EditCategoryForm;

public final class EditCategoryAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/admin/EditCategoryTemplate.jsp");
	private ActionForward DEFAULT_FORWARD_ANCHORDYNAATTRIBUTES = new ActionForward("/templates/${template.name}/admin/EditCategoryTemplate.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 {
            EditCategoryForm form = (EditCategoryForm) f;

			
			if (form.getUser().isGuestUser()
		       || !PermissionManager.hasPermission(form.getCategory().getAcl(), form.getUser(), 'c')) {
				request.setAttribute(WebShare.INFO_KEY, "category.edit.denied");
				
				return INFO_FORWARD;
			}
			
			if (request.getParameter("action.save") != null) {
				return handleSaveAction(form, request);
            } else if (request.getParameter("action.cancel") != null) {
				return handleCancelAction(form);
            } 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(EditCategoryForm.EDITMODE_CATEGORY);
				
				return DEFAULT_FORWARD;
			} else if (request.getParameter("action.delete.searchquery") != null) {
				form.setSearchQuery("");
				form.setQuery(new VKCSearchQuery());
				form.setEditMode(EditCategoryForm.EDITMODE_CATEGORY);
				
				return DEFAULT_FORWARD;
			} else if (request.getParameter("btn_query.validFrom.x") != null
			          || request.getParameter("btn_query.validUntil.x") != null) {
				form.setEditMode(EditCategoryForm.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) {
            VKCLogManager.errorLog(this, "", e.getMessage(), e);
            throw new ServletException(e);
        }
    }

    private ActionForward handleInitializeAction(EditCategoryForm form, HttpServletRequest request) throws DBException, BadLocationException {
		VKCCategory category = form.getCategory();

		form.setName(category.getName());
        form.setKeywords(category.getKeywordsAsString());

		String description = category.getDescription();

		if (!form.isTinyMCECompatible()) {
			description = VKCStringUtils.filterUnicodeChars(description);
			description = VKCStringUtils.htmlFormatedText(description);
			description = VKCStringUtils.decodeXmlEntities(description);
			description = VKCStringUtils.decodeNamedXmlEntitiesNotInSwing(description);
			description = VKCStringUtils.encodeNewLine(description);
			description = VKCStringUtils.removeHtmlTags(description);
			description = VKCStringUtils.decodeNewLine(description);
		} else {
			description = VKCStringUtils.convertNewLineInHTML(description);
		}

        form.setDescription(description);

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

    		String externalContacts = project.getExternalContacts();

    		if (!form.isTinyMCECompatible()) {
    			externalContacts = VKCStringUtils.filterUnicodeChars(externalContacts);
    			externalContacts = VKCStringUtils.htmlFormatedText(externalContacts);
    			externalContacts = VKCStringUtils.decodeXmlEntities(externalContacts);
    			externalContacts = VKCStringUtils.decodeNamedXmlEntitiesNotInSwing(externalContacts);
    			externalContacts = VKCStringUtils.encodeNewLine(externalContacts);
    			externalContacts = VKCStringUtils.removeHtmlTags(externalContacts);
    			externalContacts = VKCStringUtils.decodeNewLine(externalContacts);
    		} else {
    			externalContacts = VKCStringUtils.convertNewLineInHTML(externalContacts);
    		}

        	form.setExternalContacts(externalContacts);
        }

        if (category.getAddAttributes() != null && !category.getAddAttributes().isEmpty()) {
            for (int i = 0; i < category.getAddAttributes().size(); i++) {
                VKCAddAttribute attr = (VKCAddAttribute) category.getAddAttributes().get(i);
                
                if (BasicActionForm.isEmpty(attr.getValuestring())) {
                    form.getAddCatAttributes().put("addcatattrId_" + attr.getAttrId(), attr.getDefaultValue());
                } else {
                    form.getAddCatAttributes().put("addcatattrId_" + attr.getAttrId(), attr.getValuestring());
                }
            }
        }

        for (Iterator iter = category.getDynaAttributes().iterator(); iter.hasNext();) {
            VKCDynaAttribute dynaAttr = (VKCDynaAttribute)iter.next();
            LabelValueBean bean = new LabelValueBean(dynaAttr.getName(), dynaAttr.getValue());
            form.getDynaAttributes().add(bean);
        }
		
		VKCSearchQuery query = VKCCategorySerializer.retrieveSearchQuery(form.getCategoryId());
		form.setSearchQuery(query.getQuery());
		
		form.setEditMode(EditCategoryForm.EDITMODE_CATEGORY);

		return DEFAULT_FORWARD;
    }

    private ActionForward handleSaveAction(EditCategoryForm form, HttpServletRequest request) throws DBException {
		VKCCategory category = form.getCategory();

		category.setName(VKCStringUtils.filterUnicodeChars(form.getName()));                
        category.setKeywordsByString(VKCStringUtils.filterUnicodeChars(form.getKeywords()));
		
		String description = VKCStringUtils.filterUnicodeChars(form.getDescription());
		
		if (!form.isTinyMCECompatible()) {
			description = VKCStringUtils.decodeXmlEntities(description);
			description = VKCStringUtils.encodeNamedXmlEntities(description);
		}
		
        category.setDescription(description);
		category.setLastChanged(new Date(System.currentTimeMillis()));
        category.setLastChangerId(form.getUser().getUserId());

		if (category.isProjectCategory()) {
			VKCProject project = (VKCProject)category;
			
			String externalContacts = VKCStringUtils.filterUnicodeChars(form.getExternalContacts());
			
			if (!form.isTinyMCECompatible()) {
				externalContacts = VKCStringUtils.decodeXmlEntities(externalContacts);
				externalContacts = VKCStringUtils.encodeNamedXmlEntities(externalContacts);
			}
			
			project.setExternalContacts(externalContacts);
		}

        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)));
        }
        
        category.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);
        }
		
        category.setDynaAttributes(dynaAttributes);

		category.setAbsPathDescr(null);

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

        VKCCategorySerializer.saveCategory( category );
        
		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.getCategoryId() + "&refreshTreeView=true";
			}

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

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

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

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

		return DEFAULT_FORWARD;
	}

	private ActionForward handleCancelAction(EditCategoryForm form) {
		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.getCategoryId();
			}

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

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

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

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

		return DEFAULT_FORWARD_ANCHORDYNAATTRIBUTES;
    }
}