/*
 * $Id: SendEmailForm.java,v 1.9 2006/01/03 00:00:29 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: SendEmailForm.java,v $
 * Revision 1.9  2006/01/03 00:00:29  marbobo
 * + Absender kann frei gewählt werden
 *
 * Revision 1.8  2005/09/15 23:16:43  marbobo
 * + Sprachabhängiges Sortieren implementiert
 *
 * Revision 1.7  2004/11/12 00:24:35  marbobo
 * + getGroupInfos() in retrieveGroupInfos() umgebannt
 *
 * Revision 1.6  2004/11/10 15:02:48  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.5  2004/09/13 12:37:31  marbobo
 * + Eventhandling umgestellt
 *
 * Revision 1.4  2004/03/14 18:04:11  marbobo
 * Synchronisierung der Formdaten überarbeitet
 *
 * Revision 1.3  2004/03/13 18:18:24  marbobo
 * SendEmailAction und SendEmailForm auf Request-Scope umgestellt
 *
 * Revision 1.2  2003/12/24 10:12:06  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.1  2003/11/05 01:36:48  marbobo
 * Initiale Version
 *
 */
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.List;

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.serializer.VKCGroupSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.util.StringUtils;
import vkc.util.VKCStringUtils;
import vkc.view.bean.GroupInfo;
import vkc.view.bean.UserInfo;
import vkc.view.form.BasicActionForm;


/**
 * Form Bean zum Versenden vom Emails
 *
 * @author marbobo
 */
public final class SendEmailForm extends BasicActionForm {
	private Integer[] sendUserIds = new Integer[0];
	private Integer[] sendGroupIds = new Integer[0];
	private Integer[] selectedAddUserIds = new Integer[0];
	private Integer[] selectedAddGroupIds = new Integer[0];
	private Integer[] selectedRemoveUserIds = new Integer[0];
	private Integer[] selectedRemoveGroupIds = new Integer[0];

	private List addUsers = new ArrayList();
	private List addGroups = new ArrayList();
	private List removeUsers = new ArrayList();
	private List removeGroups = new ArrayList();

	private String sender = "";
	private String subject = "";
	private String content = "";
	
	/**
	 * 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);
	    
		sendUserIds = new Integer[0];
		sendGroupIds = new Integer[0];
		selectedAddUserIds = new Integer[0];
		selectedAddGroupIds = new Integer[0];
		selectedRemoveUserIds = new Integer[0];
		selectedRemoveGroupIds = new Integer[0];

		addUsers = new ArrayList();
		addGroups = new ArrayList();
		removeUsers = new ArrayList();
		removeGroups = new ArrayList();

		sender = getUser().getEmail();
		subject = "";
		content = "";
	}

	/**
	 * 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();

		if (request.getParameter("action.send.email") != null) {
			synchronizeForm();		

			if (isEmpty(getSender()) || !StringUtils.isEmailValid(getSender())) {
				errors.add("sender", new ActionError("vkc.administration.error.sender"));
			}
			
			if (isEmpty(getSubject())) {
				errors.add("subject", new ActionError("vkc.administration.error.subject"));
			}
		
			if (isEmpty(getContent())) {
				errors.add("content", new ActionError("vkc.administration.error.content"));
			}
		
			if (getAddUsers().isEmpty() && getAddGroups().isEmpty()) {
				errors.add("recipients", new ActionError("vkc.administration.error.recipients"));
			}
		}
		
		return errors;
	}

	public void synchronizeForm() {
		try {
			final Collator collator = Collator.getInstance(getUser().getLanguage().getLocale());

			Comparator lastname_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);
				}
			};
			
			Comparator name_c = new Comparator() {
				public int compare(Object o1, Object o2) {
					GroupInfo g1 = (GroupInfo)o1;
					GroupInfo g2 = (GroupInfo)o2;
					
                	CollationKey key1 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(g1.getName()));
                	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(g2.getName()));
                	
                	return key1.compareTo(key2);
				}
			};

			List addGroups = new ArrayList();
			List removeGroups = new ArrayList();
			List addUsers = new ArrayList();
			List removeUsers = new ArrayList();
			List groupInfos = VKCGroupSerializer.retrieveGroupInfos();
			List userInfos = VKCUserSerializer.retrieveUserInfos();
			Integer[] sendGroupIds = getSendGroupIds();
			Integer[] sendUserIds = getSendUserIds();
		
			for (int i = 0; i < sendGroupIds.length; i++) {
				for (int j = 0; j < groupInfos.size(); j++) {
					GroupInfo g = (GroupInfo)groupInfos.get(j);
					
					if (sendGroupIds[i].equals(g.getGroupId())) {
						addGroups.add(g);
						groupInfos.remove(j);
						break;
					}
				}
			}

			for (int i = 0; i < sendUserIds.length; i++) {
				for (int j = 0; j < userInfos.size(); j++) {
					UserInfo u = (UserInfo)userInfos.get(j);
					
					if (sendUserIds[i].equals(u.getUserId())) {
						addUsers.add(u);
						userInfos.remove(j);
						break;
					}
				}
			}
		
			removeGroups = groupInfos;
			removeUsers = userInfos;

			Collections.sort(addGroups, name_c);
			Collections.sort(removeGroups, name_c);
			Collections.sort(addUsers, lastname_c);
			Collections.sort(removeUsers, lastname_c);
			setAddGroups(addGroups);
			setRemoveGroups(removeGroups);
			setAddUsers(addUsers);
			setRemoveUsers(removeUsers);
		} catch (DBException e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
		}
	}

	public List getAddGroups() {
		return addGroups;
	}

	public List getAddUsers() {
		return addUsers;
	}

	public List getAddUsersSortedByUsername() {
		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.getUsername()));
            	CollationKey key2 = collator.getCollationKey(VKCStringUtils.decodeXmlEntities(u2.getUsername()));
            	
            	return key1.compareTo(key2);
			}
		};
		
		Collections.sort(addUsers, username_c);
		
		return addUsers;
	}

	public List getRemoveGroups() {
		return removeGroups;
	}

	public List getRemoveUsers() {
		return removeUsers;
	}

	public Integer[] getSendGroupIds() {
		return sendGroupIds;
	}

	public Integer[] getSendUserIds() {
		return sendUserIds;
	}

	public Integer[] getSelectedAddGroupIds() {
		return selectedAddGroupIds;
	}

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

	public Integer[] getSelectedRemoveGroupIds() {
		return selectedRemoveGroupIds;
	}

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

	public void setAddGroups(List list) {
		addGroups = list;
	}

	public void setAddUsers(List list) {
		addUsers = list;
	}

	public void setRemoveGroups(List list) {
		removeGroups = list;
	}

	public void setRemoveUsers(List list) {
		removeUsers = list;
	}

	public void setSendGroupIds(Integer[] integers) {
		sendGroupIds = integers;
	}

	public void setSendUserIds(Integer[] integers) {
		sendUserIds = integers;
	}

	public void setSelectedAddGroupIds(Integer[] integers) {
		selectedAddGroupIds = integers;
	}

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

	public void setSelectedRemoveGroupIds(Integer[] integers) {
		selectedRemoveGroupIds = integers;
	}

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

	public String getSubject() {
		return subject;
	}

	public void setSubject(String s) {
		subject = StringUtils.normalize(s);
	}

	public String getContent() {
		return content;
	}

	public void setContent(String s) {
		content = StringUtils.normalize(s);
	}

	public String getSender() {
		return sender;
	}

	public void setSender(String sender) {
		this.sender = sender;
	}
}