/*
 * $Id: RegisterGroupAction.java,v 1.4 2006/09/13 14:08:39 lawern Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: RegisterGroupAction.java,v $
 * Revision 1.4  2006/09/13 14:08:39  lawern
 * Per Default werden bei der Registrierung ab VKC4 Unterkategorien eingeschlossen.
 *
 * Revision 1.3  2005/10/05 17:02:23  marbobo
 * + Anzeigen von Kategorie oder Dokementnamen
 *
 * Revision 1.2  2005/10/03 17:33:32  marbobo
 * + Komplett-Überarbeitet und viele Fehler korrigiert
 *
 *
 */
package vkc.view.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

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.view.bean.RegisteredCategory;
import vkc.view.bean.RegisteredDocument;
import vkc.view.form.RegisterGroupForm;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCGroupSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.view.WebShare;

/**
 * Action-Klasse zum Registrieren eines Objektes für die ganze Gruppe
 */
public final class RegisterGroupAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/admin/RegisterGroup.jsp");

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

	/**
	 * Hier werden die entsprechenden Aktionen eingeleitet (Gruppendaten
	 * speichern, Gruppenbenutzer verändern)
	 */
	public ActionForward execute( ActionMapping mapping, 
	        					  ActionForm f,
	        					  HttpServletRequest request, 
	        					  HttpServletResponse response )
	throws Exception {
		RegisterGroupForm form = (RegisterGroupForm) f;
		VKCUser user = form.getUser();

		if (!user.hasAdminPrivileges() && !user.isDedicatedAdmin()) {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");

			return INFO_FORWARD;
		}

		if (request.getParameter("action.register") != null) {
			return handleRegisterAction(form, request);
		} else if (request.getParameter("action.back") != null) {
			return new ActionForward(form.getRedirectPath(), true);
		} else if (request.getParameter("action.add.groupToRegister") != null) {
			return handleAddGroupToRegisterAction(form, request);
		} else if (request.getParameter("action.remove.groupFromRegister") != null) {
			return handleRemoveGroupFromRegisterAction(form,	request);
		}  else if (request.getParameter("action.add.userToRegister") != null) {
			return handleAddUserToRegisterAction(form, request);
		} else if (request.getParameter("action.remove.userFromRegister") != null) {
			return handleRemoveUserFromRegisterAction(form,	request);
		} else {
			return handleInitializeAction(form, request);
		}
	}

	private void synchronizeForm(RegisterGroupForm form, HttpServletRequest request) {
		form.synchronizeForm(request);
	}

	private ActionForward handleAddGroupToRegisterAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		Integer[] addIds = form.getSelectedAddGroupIds();
		List addGroupIds = new ArrayList(Arrays.asList(form.getAddGroupIds()));
		
		for (int i = 0; i < addIds.length; i++) {
			if (!addGroupIds.contains(addIds[i])) {
				addGroupIds.add(addIds[i]);
			}
		}
		
		form.setAddGroupIds((Integer[])addGroupIds.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleRemoveGroupFromRegisterAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		Integer[] removeIds = form.getSelectedRemoveGroupIds();
		List addGroupIds = new ArrayList(Arrays.asList(form.getAddGroupIds()));
		
		for (int i = 0; i < removeIds.length; i++) {
			if (addGroupIds.contains(removeIds[i])) {
				addGroupIds.remove(removeIds[i]);
			}
		}
		
		form.setAddGroupIds((Integer[])addGroupIds.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}
	
	private ActionForward handleAddUserToRegisterAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		Integer[] addIds = form.getSelectedAddUserIds();
		List addUserIds = new ArrayList(Arrays.asList(form.getAddUserIds()));
		
		for (int i = 0; i < addIds.length; i++) {
			if (!addUserIds.contains(addIds[i])) {
				addUserIds.add(addIds[i]);
			}
		}
		
		form.setAddUserIds((Integer[])addUserIds.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleRemoveUserFromRegisterAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		Integer[] removeIds = form.getSelectedRemoveUserIds();
		List addUserIds = new ArrayList(Arrays.asList(form.getAddUserIds()));
		
		for (int i = 0; i < removeIds.length; i++) {
			if (addUserIds.contains(removeIds[i])) {
				addUserIds.remove(removeIds[i]);
			}
		}
		
		form.setAddUserIds((Integer[])addUserIds.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}
	
	private ActionForward handleInitializeAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}

	/**
	* Diese Methode registriert Daten für die Mitglieder allen ausgewählten Gruppen 
	* 
	*/
	public ActionForward handleRegisterAction(RegisterGroupForm form, HttpServletRequest request) throws Exception {
		VKCUser user = null;
		Integer[] addGroupIds = form.getAddGroupIds();
		Integer[] addUserIds = form.getAddUserIds();
		Set registeredCategoryUserIds = new HashSet();
		Set registeredDocumentUserIds = new HashSet();
		
		//Falls keine Kategorie vorliegt ist nichts zutun
		if (form.getCategoryId() != null && form.getCategoryId().intValue() > 0) {
			//für die uasgewählte User registrieren
			for (int i = 0; i < addUserIds.length; i++) {
	        	user = VKCUserSerializer.retrieveUser(addUserIds[i]);
	        	
		        if (form.getDocumentId() == null || form.getDocumentId().intValue() <= 0) {
					registeredCategoryUserIds.add(addUserIds[i]);
		        	user.retrieveRegisteredCategories();

		        	if (!user.isRegisteredCategory(form.getCategoryId())) {
	    				//Kategorie registrieren
	    				RegisteredCategory category = new RegisteredCategory();
	    				category.setCategoryId(form.getCategoryId());
	    				category.setIncludeSubDirs(Boolean.TRUE);
	    				user.addRegisteredCategory(category);
	    				user.saveRegisteredCategories();
	    			}
	        	} else {
					registeredDocumentUserIds.add(addUserIds[i]);
		        	user.retrieveRegisteredDocuments();

		        	if (!user.isRegisteredDocument(form.getDocumentId())) {
	    				//Document registrieren
	    				RegisteredDocument document = new RegisteredDocument();
	    				document.setDocumentId(form.getDocumentId());
	    				document.setThreshold(new Integer(10));
	    				user.addRegisteredDocument(document);
	    				user.saveRegisteredDocuments();
	    			}
	        	}
	        }
			
	        // für ausgewählte Gruppen  registrieren
	   		for (int i = 0; i < addGroupIds.length; i++) {
			    Set userIds =  VKCGroupSerializer.getGroupUserIds(addGroupIds[i]);
	            Iterator iter = userIds.iterator();
	            
	            while (iter.hasNext()) {
	                Integer userId = (Integer)iter.next();
	            	
	                if (form.getDocumentId() == null || form.getDocumentId().intValue() <= 0) {
		                if (!registeredCategoryUserIds.contains(userId)) {
		    				registeredCategoryUserIds.add(userId);
		                	user = VKCUserSerializer.retrieveUser(userId);
		    	        	user.retrieveRegisteredCategories();

		                	if (!user.isRegisteredCategory(form.getCategoryId())) {
			    				//Kategorie registrieren
			    				RegisteredCategory category = new RegisteredCategory();
			    				category.setCategoryId(form.getCategoryId());
			    				category.setIncludeSubDirs(Boolean.TRUE);
			    				user.addRegisteredCategory(category);
			    				user.saveRegisteredCategories();
			    			}
		                }
	            	} else {
	            		if (!registeredDocumentUserIds.contains(userId)) {
		    				registeredDocumentUserIds.add(userId);
		                	user = VKCUserSerializer.retrieveUser(userId);
		    	        	user.retrieveRegisteredDocuments();

		    	        	if (!user.isRegisteredDocument(form.getDocumentId())) {
	    	    				//Document registrieren
	    	    				RegisteredDocument document = new RegisteredDocument();
	    	    				document.setDocumentId(form.getDocumentId());
	    	    				document.setThreshold(new Integer(10));
	    	    				user.addRegisteredDocument(document);
	    	    				user.saveRegisteredDocuments();
	    	    			}
	            		}
	            	}
	    		}           
	        }
		
	    	if (addUserIds.length > 0 || addGroupIds.length > 0) {
	    		if (form.getDocumentId() == null || form.getDocumentId().intValue() <= 0) {
		            request.setAttribute(WebShare.INFO_KEY, "vkc.admin.registerGroup.category.registered");
			    } else {
		       		request.setAttribute(WebShare.INFO_KEY, "vkc.admin.registerGroup.document.registered");
			    }
	    	}
		}
		
        return new ActionForward(form.getRedirectPath(), true);
	}
}