/*
 * $Id: ClusterResultSaveAction.java,v 1.4 2006/10/04 03:14:33 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ClusterResultSaveAction.java,v $
 * Revision 1.4  2006/10/04 03:14:33  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.3  2005/10/13 11:30:17  lawern
 * Problem mit zu langen Kategorienamen des Cluster-Moduls behoben.
 *
 * Revision 1.2  2005/06/29 21:15:50  marbobo
 * + Clustern ist nun aktivierbar/deaktivierbar
 *
 * Revision 1.1  2005/06/23 00:58:29  aram
 * + Initiale Version
 *
 */
package vkc.view.action;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.HashSet;
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.clusterer.ClusteringItem;
import vkc.clusterer.Clustern;
import vkc.db.entities.VKCAclEntry;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCDocument;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCSysParameterSerializer;
import vkc.security.PermissionManager;
import vkc.security.VKCAcl;
import vkc.util.ObjectCloner;
import vkc.util.StringUtils;
import vkc.util.treeview.TreeView;
import vkc.util.treeview.TreeViewItem;
import vkc.view.WebShare;
import vkc.view.form.ClusterResultSaveForm;

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

    		if (VKCSysParameterSerializer.retrieveIntValue("CATEGORYVIEW", "EnableClusterCategory", 0) == 0) {
    			request.setAttribute(WebShare.INFO_KEY, "vkc.info.action_not_allowed");
                
    			return INFO_FORWARD;
    		}

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

            if (request.getParameter("action.save") != null) {
				return handleSaveAction(form, request);
            } else if (request.getParameter("action.cancel") != null) {
				return handleCancelAction(form, request);
            } else {
                return handleInitializeAction(form, request);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

	private ActionForward handleInitializeAction(ClusterResultSaveForm form, HttpServletRequest request) {
	    return DEFAULT_FORWARD;
	}
	
	private ActionForward handleSaveAction(ClusterResultSaveForm form, HttpServletRequest request) throws Exception {
        HashMap clusters = (HashMap)request.getSession().getAttribute(Clustern.CLUSTER_MAP_NAME);
		TreeView tree = (TreeView)request.getSession().getAttribute(TreeView.CLUSTER_TREE_KEY);
	    Integer parentId = form.getCategoryId();
	    ClusteringItem rootCluster = (ClusteringItem)clusters.get(new Integer(-1));
	    
	    if (rootCluster != null) {
	        for (Iterator iter = rootCluster.getSubCluster().iterator(); iter.hasNext();) {
                Integer clusterId = (Integer) iter.next();
                
                saveClusters(clusterId, parentId, clusters, tree, form);
            }
	    }

	    return handleCancelAction(form, request);
	}
	
    private void saveClusters(Integer clusterId, Integer parentId, HashMap clusters, TreeView tree, ClusterResultSaveForm form) throws Exception{
        ClusteringItem cluster = (ClusteringItem)clusters.get(clusterId);
        
        if (cluster != null) {
            TreeViewItem item = tree.getTreeViewItemById(clusterId.toString());
            
            if (item.isChecked()) {
                if (cluster.isPlaneHierarchy()) {
                    HashSet documentIds = cluster.getRecursivDocumentIds();
                    
                    for (Iterator iter = cluster.getSubCluster().iterator(); iter.hasNext();) {
                        Integer scid = (Integer) iter.next();
                        
                        removeDocumentIds(scid, clusters, tree, documentIds);
                    }
                    
                    saveCategory(cluster, parentId, documentIds, form);
                    
                    return;
                }

                parentId = saveCategory(cluster, parentId, cluster.getDocumentIds(), form);
            }

	        for (Iterator iter = cluster.getSubCluster().iterator(); iter.hasNext();) {
                Integer scid = (Integer) iter.next();
                
                saveClusters(scid, parentId, clusters, tree, form);
            }
        }
    }

    private Integer saveCategory(ClusteringItem cluster, Integer parentId, HashSet documentIds, ClusterResultSaveForm form) throws Exception {
        VKCCategory category = new VKCCategory();
        category.setName(StringUtils.isEmpty(cluster.getName()) ? "Cluster_" + new Timestamp(System.currentTimeMillis()) : cluster.getName());
        category.setDescription(cluster.getDescription());
        category.setParentCategoryId(parentId);
        
        VKCAcl acl = (VKCAcl)ObjectCloner.deepCopy(form.getCategory().getAcl());
        acl.setAclId(null);
        
        for (Iterator iter = acl.getAclEntries().iterator(); iter.hasNext();) {
            VKCAclEntry ae = (VKCAclEntry) iter.next();
            
            ae.setCreated(new Timestamp(System.currentTimeMillis()));
            ae.setCreatorId(form.getUser().getUserId());
        }
        
        category.setAcl(acl);
        category.setCreated(new Timestamp(System.currentTimeMillis()));
        category.setCreatorId(form.getUser().getUserId());
        VKCCategorySerializer.saveCategory(category);
        
        for (Iterator iter = documentIds.iterator(); iter.hasNext();) {
            Integer id = (Integer) iter.next();
            VKCDocument doc = new VKCDocument();
            doc.setDocumentId(id);
            int i = form.getCategory().getDocuments().indexOf(doc);
            VKCDocument document = (VKCDocument)form.getCategory().getDocuments().remove(i);
            document.setCategoryId(category.getCategoryId());
            VKCDocumentSerializer.saveDocument(document, true, false);
        }
        
        return category.getCategoryId();
    }

    private void removeDocumentIds(Integer clusterId, HashMap clusters, TreeView tree, HashSet documentIds) {
        ClusteringItem cluster = (ClusteringItem)clusters.get(clusterId);
        
        if (cluster != null) {
            TreeViewItem item = tree.getTreeViewItemById(clusterId.toString());
            
            if (!item.isChecked()) {
                documentIds.removeAll(cluster.getDocumentIds());
            }

            for (Iterator iter = cluster.getSubCluster().iterator(); iter.hasNext();) {
                Integer scid = (Integer) iter.next();
                
                removeDocumentIds(scid, clusters, tree, documentIds);
            }
        }
    }

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

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