/*
 * $Id: EditGroupAction.java,v 1.23 2006/10/04 03:15:00 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: EditGroupAction.java,v $
 * Revision 1.23  2006/10/04 03:15:00  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.22  2006/03/09 01:22:50  marbobo
 * + Bugfix
 *
 * Revision 1.21  2005/02/20 16:56:23  marbobo
 * + Beim Speichern der Entities in die Datenbank wird sichergestellt
 *    dass Unicode-Zeichen in Kodierterform (als &#xxxxx;) gespeichert werden
 *
 * Revision 1.20  2005/02/14 14:01:47  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.19  2004/09/16 13:10:55  marbobo
 * + Auf VKCRequestProcessor umgestellt
 *
 * Revision 1.18  2004/08/30 20:06:35  marbobo
 * + Verbesserung des Redirectmechanismus
 *
 * Revision 1.17  2004/08/07 00:34:44  marbobo
 * + Bugfix für Zeitangaben und Refactorings
 *
 * Revision 1.16  2004/07/13 22:33:23  marbobo
 * + Sicherheitsüberprüfungen
 *
 * Revision 1.15  2004/06/21 11:51:30  marbobo
 * + Gruppenname nachträglich (fals möglich) editieren
 *
 * Revision 1.14  2004/03/14 18:04:11  marbobo
 * Synchronisierung der Formdaten überarbeitet
 *
 * Revision 1.13  2004/03/13 14:48:58  marbobo
 * EditGroupAction und EditGroupForm auf Request-Scope umgestellt
 *
 * Revision 1.12  2004/03/11 20:17:15  bigmac
 * Anpassungen an VKCUserSerializer
 *
 * Revision 1.11  2004/03/07 13:45:48  bigmac
 * Anpassungen an VKCDocumentTypeSerializer, VKCDocumentClassSerializer, VKCDocumentStatusSerializer
 *
 * Revision 1.10  2004/03/02 17:46:56  bigmac
 * Anpassungen an VKCGroupSerializer
 *
 * Revision 1.9  2004/01/26 13:55:25  marbobo
 * +Benutzer- und Gruppenverwaltung für dedizierte Administratoren
 *
 * Revision 1.8  2003/12/24 10:12:09  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.7  2003/10/31 00:38:06  marbobo
 * +Gültig von und Gültig bis editierbar
 *
 * Revision 1.6  2003/09/08 16:59:02  marbobo
 * *** empty log message ***
 *
 * Revision 1.5  2003/08/27 11:11:10  marbobo
 * "Zurück"-Button-Funktionalität eingebaut
 *
 * Revision 1.4  2003/08/23 21:55:22  marbobo
 * Rückgabewert der Methoden getAllUserInfos() und getAllGroupInfos()
 * von Vector nach HashMap umgestellt.
 *
 * Revision 1.3  2003/08/20 17:47:43  marbobo
 * Benutzergruppen werden nun effizient abgespeichert
 *
 * Revision 1.2  2003/08/20 11:19:59  marbobo
 * Nullpointer abgefangen
 *
 * Revision 1.1  2003/08/18 21:11:46  marbobo
 * Package verschoben
 *
 */
package vkc.administration.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

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.administration.form.EditGroupForm;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCGroupSerializer;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.WebShare;


/**
 * Action-Klasse zum Editieren eines Gruppen-Objektes
 *
 * @author marbobo
 * @version $Revision: 1.23 $
 */
public final class EditGroupAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/administration/editGroup.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 {
		EditGroupForm form = (EditGroupForm) f;
		VKCUser user = form.getUser();

		if (!user.hasAdminPrivileges() 
		    && !user.getManageOwnGroups() 
          	&& form.getGroup() == null 
           	&& !user.getUserId().equals(form.getGroup().getCreatorId())) {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");

			return INFO_FORWARD;
		}

		if (request.getParameter("action.save.group") != null) {
			return handleSaveGroupAction(form, request);
		} else if (request.getParameter("action.back") != null) {
			return new ActionForward(form.getRedirectPath());
		} else if (request.getParameter("action.add.usersToGroup") != null) {
			return handleAddUsersToGroupAction(form, request);
		} else if (request.getParameter("action.remove.usersFromGroup") != null) {
			return handleRemoveUsersFromGroupAction(form,	request);
		} else {
			return handleInitializeAction(form, request);
		}
	}

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

	private ActionForward handleAddUsersToGroupAction(EditGroupForm 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 handleRemoveUsersFromGroupAction(EditGroupForm 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(EditGroupForm form, HttpServletRequest request) throws Exception {
		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD;
	}

	/**
	* Diese Methode speichert alle Gruppendaten permanent in die  Datenbank
	* ab
	*/
	public ActionForward handleSaveGroupAction(EditGroupForm form, HttpServletRequest request) throws Exception {
		//Gruppenspezifische Variablen setzen oder initialisieren
		VKCUser user = form.getUser();
		Integer[] addUserIds = (Integer[])form.getAddGroupUserIds().toArray(new Integer[0]);
		Integer[] removeUserIds = (Integer[])form.getRemoveGroupUserIds().toArray(new Integer[0]);

		VKCGroupSerializer.deleteGroupUsers(form.getGroup().getGroupId(), removeUserIds);
		VKCGroupSerializer.saveGroupUsers(form.getGroup().getGroupId(), addUserIds, user.getUserId());
		
		form.getGroup().setName(VKCStringUtils.filterUnicodeChars(form.getGroupname()));
		form.getGroup().setDescription(VKCStringUtils.filterUnicodeChars(form.getDescription()));
		form.getGroup().setAccountValid(Boolean.valueOf(form.isAccountValid()));
		
		if (user.hasAdminPrivileges()) {
			form.getGroup().setAdminPrivileges(Boolean.valueOf(form.isAdminPrivileges()));
		}

		//Gruppengültigkeit ermitteln und setzen
		if (form.getGroup().getAccountValid().booleanValue()) {
			String from = form.getValidFrom();
			String until = form.getValidUntil();
			
			if (!StringUtils.isEmpty(from)) {
				Date d = DateUtils.parseDate(from);
				form.getGroup().setValidFrom(new Timestamp(d.getTime()));
			} else {
				form.getGroup().setValidFrom(null);
			}
			
			if (!StringUtils.isEmpty(until)){
				Date d = DateUtils.parseDate(until);
				Calendar c = Calendar.getInstance();
				c.setTime(d);
				c.set(Calendar.HOUR_OF_DAY, 23);
				c.set(Calendar.MINUTE, 59);
				c.set(Calendar.SECOND, 59);
				form.getGroup().setValidUntil(new Timestamp(c.getTimeInMillis()));
			} else {
				form.getGroup().setValidUntil(null);
			}
		} else {
			form.getGroup().setValidFrom(null);
			form.getGroup().setValidUntil(null);
		}

		//Gruppenobjekt in die Datenbank abspeicher
		form.getGroup().setLastChanged(new Timestamp(System.currentTimeMillis()));
		form.getGroup().setLastChangerId(user.getUserId());
		
		VKCGroupSerializer.saveGroup(form.getGroup());

		form.setGroupId(form.getGroup().getGroupId());
		
		if (form.getAddGroupUserIds().contains(user.getUserId())) {
			if (!user.isMemberOf(form.getGroup().getGroupId())) {
				user.addGroup(form.getGroup());
				request.getSession().setAttribute(WebShare.USER_KEY, user);
			}
		} else if (form.getRemoveGroupUserIds().contains(user.getUserId())) {
			if (user.isMemberOf(form.getGroup().getGroupId())) {
				user.removeGroup(form.getGroup());
				request.getSession().setAttribute(WebShare.USER_KEY, user);
			}
		}
		
		return handleInitializeAction(form, request);
	}
}