/*
 * $Id: EditGroupForm.java,v 1.21 2006/04/29 18:39:47 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: EditGroupForm.java,v $
 * Revision 1.21  2006/04/29 18:39:47  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.20  2005/09/15 13:52:59  marbobo
 * + Sortierung der Benutzerliste nach Nachnamen umgestellt
 *
 * Revision 1.19  2005/09/15 13:39:07  marbobo
 * + Sprachabhängige Sortierung implementiert
 *
 * Revision 1.18  2005/09/01 09:54:52  jonyp
 * retrieve only valid user infos for the userlist
 *
 * Revision 1.17  2005/02/20 23:34:15  marbobo
 * + Bugfix
 *
 * Revision 1.16  2004/11/10 15:02:48  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.15  2004/08/30 20:06:35  marbobo
 * + Verbesserung des Redirectmechanismus
 *
 * Revision 1.14  2004/08/07 00:34:43  marbobo
 * + Bugfix für Zeitangaben und Refactorings
 *
 * Revision 1.13  2004/06/21 11:51:30  marbobo
 * + Gruppenname nachträglich (fals möglich) editieren
 *
 * Revision 1.12  2004/04/18 14:34:18  marbobo
 * Bugfix
 *
 * Revision 1.10  2004/03/14 18:04:11  marbobo
 * Synchronisierung der Formdaten überarbeitet
 *
 * Revision 1.9  2004/03/13 14:48:58  marbobo
 * EditGroupAction und EditGroupForm auf Request-Scope umgestellt
 *
 * Revision 1.8  2004/03/02 17:46:56  bigmac
 * Anpassungen an VKCGroupSerializer
 *
 * Revision 1.7  2003/12/24 10:12:06  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.6  2003/11/03 11:41:48  marbobo
 * - CreateGroups entfernt
 *
 * Revision 1.5  2003/10/31 00:38:06  marbobo
 * +Gültig von und Gültig bis editierbar
 *
 * Revision 1.4  2003/10/05 01:40:55  marbobo
 * +accountValid bei Gruppen
 * +Sperren und Aktivieren von Gruppen
 * +Verbesserungen
 *
 * Revision 1.3  2003/08/27 11:11:10  marbobo
 * "Zurück"-Button-Funktionalität eingebaut
 *
 * Revision 1.2  2003/08/20 17:51:11  marbobo
 * Nullpointer abgefangen
 *
 * Revision 1.1  2003/08/18 21:11:49  marbobo
 * Package verschoben
 *
 */
package vkc.administration.form;

import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCGroup;
import vkc.db.serializer.VKCGroupSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.bean.UserInfo;
import vkc.view.form.BasicActionForm;

/**
 * Form Bean zum Editieren von Gruppenprofilen
 *
 * @author marbobo
 * @version $Revision: 1.21 $
 */
public final class EditGroupForm extends BasicActionForm {
	//~ Instance fields --------------------------------------------------------

	private boolean		accountValid			= false;
	private boolean		adminPrivileges			= false;

	private Integer  	groupId     			= null;
	private Integer[]	addUserIds				= new Integer[0];	
	private Integer[]	selectedAddUserIds		= new Integer[0];	
	private Integer[]	selectedRemoveUserIds	= new Integer[0];	
	
	private List		addUserLabels			= new ArrayList();
	private List		removeUserLabels		= new ArrayList();

	private String		groupname				= "";
	private String		description				= "";
	private String 		validFrom		   		= "";
	private String 		validUntil		   		= "";
	private String		redirect				= "";
	private String  creationDate = null;
    private String  lastEditingDate = null;

    public String getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(String creationDate) {
        this.creationDate = creationDate;
    }

    public String getLastEditingDate() {
        return lastEditingDate;
    }

    public void setLastEditingDate(String lastEditingDate) {
        this.lastEditingDate = lastEditingDate;
    }

    public UserInfo getCreator() {
        return creator;
    }

    public void setCreator(UserInfo creator) {
        this.creator = creator;
    }

    public UserInfo getLastEditor() {
        return lastEditor;
    }

    public void setLastEditor(UserInfo lastEditor) {
        this.lastEditor = lastEditor;
    }

    private UserInfo creator = null;
    private UserInfo lastEditor = null;
	
	private VKCGroup 	group 					= null;
	//~ Methods ----------------------------------------------------------------

	/**
	 * Reset der Eingabefelder auf Defaultwerte
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		super.reset(mapping, request);

		accountValid			= false;
		adminPrivileges			= false;

		groupId     			= null;
		addUserIds				= new Integer[0];	
		selectedAddUserIds		= new Integer[0];	
		selectedRemoveUserIds	= new Integer[0];	
		
		addUserLabels			= new ArrayList();
		removeUserLabels		= new ArrayList();

		groupname				= "";
		description				= "";
		validFrom		   		= "";
		validUntil		   		= "";
		redirect				= "";
		
		group 					= null;
	}

	/**
	 * Validiert die Eingabefelder und gibt gegebenfalls die Fehler zurück
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();

		setAccountValid(request.getParameter("accountValid") != null);
		setAdminPrivileges(request.getParameter("adminPrivileges") != null);

		if (request.getParameter("action.save.group") != null) {
			synchronizeForm(request);

			String from  = getValidFrom();
			String until = getValidUntil();
			Date f = null;
			Date u = null;
				
			if (!isEmpty(from)) {
				if ((f = DateUtils.parseDate(from)) == null) {
					errors.add("validFrom", new ActionError("error.date"));
				}
			}

			if (!isEmpty(until)) {
				if ((u = DateUtils.parseDate(until)) == null) {
					errors.add("validUntil", new ActionError("error.date"));
				}
			}
				
			if (f != null && u != null && f.after(u)) {
				errors.add("date", new ActionError("error.date.range"));
			}

			if (isEmpty(getGroupname())) {
				errors.add("groupname", new ActionError("vkc.administration.error.groupname.required"));
			}
			
			
			
			try {
				if (!getGroup().getName().equals(VKCStringUtils.filterUnicodeChars(getGroupname())) && VKCGroupSerializer.isGroupExistent(VKCStringUtils.filterUnicodeChars(getGroupname()))) {
					errors.add("groupname.exist", new ActionError("vkc.administration.error.groupname.exist"));
				}
				if ( group != null ) {
	                setCreator( VKCUserSerializer.retrieveUserInfo( group.getCreatorId() ) );
	                
	                if ( group.getCreated() != null ) {
	                    Date d = new Date( group.getCreated().getTime() );
	                    setCreationDate( DateUtils.getDD_MM_YYYY( d ) + ", " + DateUtils.getHH_MM_SS( d ) );
	                }

	                if( group.getLastChangerId()!=null){
	                    setLastEditor( VKCUserSerializer.retrieveUserInfo( group.getLastChangerId() ) );
	                }
	                if ( group.getLastChanged() != null ) {
	                    Date d = new Date( group.getLastChanged().getTime() );
	                    setLastEditingDate( DateUtils.getDD_MM_YYYY( d ) + ", " + DateUtils.getHH_MM_SS( d ) );
	                }
	            }
			} catch (DBException e) {
				VKCLogManager.errorLog(this, "", e.getMessage(), e);
			}
		}

		return errors;
	}
	
	public void synchronizeForm(HttpServletRequest request) {
		try {
			setGroup(VKCGroupSerializer.retrieveGroup(getGroupId()));

			if (request.getParameter("initialize") != null) {
				if (getGroup().getValidFrom() != null) {
					Date from = new Date(getGroup().getValidFrom().getTime());
					setValidFrom(DateUtils.getDD_MM_YYYY(from));
				} else {
					setValidFrom("");
				}

				if (getGroup().getValidUntil() != null) {
					Date until = new Date(getGroup().getValidUntil().getTime());
					setValidUntil(DateUtils.getDD_MM_YYYY(until));
				} else {
					setValidUntil("");
				}
			
				if (getGroup().getDescription() != null) {
					setDescription(getGroup().getDescription());
				}
			
				setGroupname(getGroup().getName());
				setAdminPrivileges(getGroup().getAdminPrivileges().booleanValue());
				setAccountValid(getGroup().getAccountValid().booleanValue());
				setAddUserIds((Integer[]) getGroup().getGroupUserIds().toArray(new Integer[0]));
			}
		
			List addUserLabels = new ArrayList();
			List removeUserLabels = new ArrayList();
			List userInfos = VKCUserSerializer.retrieveValidUserInfos();
			Integer[] addUserIds = getAddUserIds();

			for (int i = 0; i < addUserIds.length; i++) {
				for (int j = 0; j < userInfos.size(); j++) {
					UserInfo user = (UserInfo) userInfos.get(j);
					
					if (addUserIds[i].equals(user.getUserId())) {
						addUserLabels.add(user);
						userInfos.remove(j);
						break;
					}
				}
			}
	
			removeUserLabels = userInfos;
			final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());

			Comparator username_c = new Comparator() {
				public int compare(Object o1, Object o2) {
					UserInfo u1 = (UserInfo) o1;
					UserInfo u2 = (UserInfo) o2;
					
                	CollationKey key1 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u1.getLastname()));
                	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getLastname()));
                	
                	return key1.compareTo(key2);
				}
			};

			Collections.sort(addUserLabels, username_c);
			Collections.sort(removeUserLabels, username_c);
			setAddUserLabels(addUserLabels);
			setRemoveUserLabels(removeUserLabels);
			if ( group != null ) {
                setCreator( VKCUserSerializer.retrieveUserInfo( group.getCreatorId() ) );
                
                if ( group.getCreated() != null ) {
                    Date d = new Date( group.getCreated().getTime() );
                    setCreationDate( DateUtils.getDD_MM_YYYY( d ) + ", " + DateUtils.getHH_MM_SS( d ) );
                }

                if( group.getLastChangerId()!=null){
                    setLastEditor( VKCUserSerializer.retrieveUserInfo( group.getLastChangerId() ) );
                }
                if ( group.getLastChanged() != null ) {
                    Date d = new Date( group.getLastChanged().getTime() );
                    setLastEditingDate( DateUtils.getDD_MM_YYYY( d ) + ", " + DateUtils.getHH_MM_SS( d ) );
                }
            }
		} catch (DBException e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
		}
	}

	public List getAddUserLabels() {
		return addUserLabels;
	}

	public VKCGroup getGroup() {
		return group;
	}

	public List getRemoveUserLabels() {
		return removeUserLabels;
	}

	public Integer[] getAddUserIds() {
		return addUserIds;
	}

	public Integer[] getSelectedAddUserIds() {
		return selectedAddUserIds;
	}

	public Integer getGroupId() {
		return groupId;
	}

	public Integer[] getSelectedRemoveUserIds() {
		return selectedRemoveUserIds;
	}

	public void setAddUserLabels(List list) {
		addUserLabels = list;
	}

	public void setGroup(VKCGroup group) {
		this.group = group;
	}

	public void setRemoveUserLabels(List list) {
		removeUserLabels = list;
	}

	public void setAddUserIds(Integer[] integers) {
		addUserIds = integers;
	}

	public void setSelectedAddUserIds(Integer[] ids) {
		selectedAddUserIds = ids;
	}

	public void setGroupId(Integer integer) {
		groupId = integer;
	}

	public void setSelectedRemoveUserIds(Integer[] ids) {
		selectedRemoveUserIds = ids;
	}

	public String getValidFrom() {
		return validFrom;
	}

	public void setValidFrom(String s) {
		validFrom = StringUtils.normalize(s);
	}

	public String getValidUntil() {
		return validUntil;
	}

	public void setValidUntil(String s) {
		validUntil = StringUtils.normalize(s);
	}

	public boolean isAccountValid() {
		return accountValid;
	}

	public boolean isAdminPrivileges() {
		return adminPrivileges;
	}

	public void setAccountValid(boolean b) {
		accountValid = b;
	}

	public void setAdminPrivileges(boolean b) {
		adminPrivileges = b;
	}

	public void setDescription(String s) {
		description = StringUtils.normalize(s);
	}

	public String getDescription() {
		return description;
	}

	public Set getAddGroupUserIds() {
		Set userIds = new HashSet();
		
		for (int i = 0; i < addUserLabels.size(); i++) {
			UserInfo u = (UserInfo)addUserLabels.get(i);
			userIds.add(new Integer(u.getUserId().intValue()));
		}
		
		return userIds;
	}

	public Set getRemoveGroupUserIds() {
		Set userIds = new HashSet();
		
		for (int i = 0; i < removeUserLabels.size(); i++) {
			UserInfo u = (UserInfo)removeUserLabels.get(i);
			userIds.add(new Integer(u.getUserId().intValue()));
		}
		
		return userIds;
	}

	public String getRedirect() {
	    return redirect;
	}
	
	public String getRedirectPath() {
	    if (!isEmpty(getRedirect())) {
		    return VKCStringUtils.base64Decode(getRedirect());
	    }
	    
	    return "/groupList.do";
	}
	
	public void setRedirect(String s) {
	    redirect = StringUtils.normalize(s);
	}
	
	public String getGroupname() {
		return groupname;
	}

	public void setGroupname(String s) {
		groupname = StringUtils.normalize(s);
	}
}