/*
 * $Id: EditMessengerForm.java,v 1.16 2008/02/12 09:39:57 korowa Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: EditMessengerForm.java,v $
 * Revision 1.16  2008/02/12 09:39:57  korowa
 * + Eine Möglichkeit für den Benutzer hinzugefügt die Emailsart auszuwählen (HTML oder Plaintext)
 * + Betreff für den Messenger der als Emailsubject bei Benachrichtigung übers erscheinen von VKC Dokumenten verschickt wird.
 *
 * Revision 1.15  2006/10/29 17:25:31  marbobo
 * + Überprüfung der Syntax für Suchanfragen
 *
 * Revision 1.14  2005/09/05 22:45:19  marbobo
 * + Suche nach Metadaten-Attribute (Erstellungsdatum) für Dokumente implementiert
 *
 * Revision 1.13  2004/11/10 15:02:54  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.12  2004/10/06 12:33:38  marbobo
 * + Suche nach Globalen Dokument-Attributen korrigiert
 *
 * Revision 1.11  2004/10/05 17:59:50  marbobo
 * + Suche nach Globalen Dokument-Attributen überarbeitet
 *
 * Revision 1.10  2004/08/26 22:11:27  marbobo
 * + Umgeschrieben wegen Queries
 *
 * Revision 1.9  2004/08/20 15:42:53  jonyp
 * refactoring due to change of VKCSearchQuerySerializer to VKCUserRegSearchQuerySerializer
 *
 * Revision 1.8  2004/08/20 12:46:43  koppy
 * Verwaltung von Quries
 *
 * Revision 1.7  2004/03/16 21:14:41  marbobo
 * Überarbeitet
 *
 * Revision 1.6  2003/12/24 10:12:13  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.5  2003/12/17 14:44:27  bigmac
 * +Intervallcheck für Schwellwerte eingefügt
 * +Schlüsselwortverarbeitung zeilenbasiert
 *
 * Revision 1.4  2003/10/04 16:49:17  marbobo
 * +Dokumentregistrieren
 *
 * Revision 1.3  2003/10/04 02:28:59  marbobo
 * +Kategorienregistrieren mit Unterordnern
 * +kleine Verbesserungen
 * +Dokumenteregistrieren (noch ohne Funktion)
 *
 * Revision 1.2  2003/08/07 01:57:05  marbobo
 * Bugfix
 *
 * Revision 1.1  2003/08/06 19:40:25  marbobo
 * Initial Version
 *
 */
package vkc.messenger.form;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
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.entities.VKCKeyword;
import vkc.db.entities.VKCSearchQuery;
import vkc.db.entities.VKCUser;
import vkc.exception.DBException;
import vkc.misc.VKCLogManager;
import vkc.search.Search;
import vkc.util.DateUtils;
import vkc.util.sort.KeywordsSortFactory;
import vkc.view.bean.RegisteredCategory;
import vkc.view.bean.RegisteredDocument;
import vkc.view.form.DynaForm;


/**
 * Form Bean zum Editieren von Benachrichtigungseinstellungen
 *
 * @author marbobo
 * @version $Revision: 1.16 $
 */
public final class EditMessengerForm extends DynaForm {
	public static final String EDITMODE_MESSENGER	= "EDITMESSENGER";
	public static final String EDITMODE_SEARCHQUERY	= "SEARCHQUERY";
	
    //~ Instance fields --------------------------------------------------------
	private boolean messagingEnabled = false;

	private Integer selectedId	= null;
	private Integer uniqueId 	= new Integer(0);
	
	private Integer[] queryIds	    		= new Integer[0];
	private Integer[] selectedCategoryIds	= new Integer[0];
	private Integer[] selectedSubDirIds	    = new Integer[0];
	private Integer[] selectedDocumentIds	= new Integer[0];
	private Integer[] selectedQueryIds	    = new Integer[0];

	
	private String editMode						= EDITMODE_MESSENGER;
	private String keywordsString				= "";
	private String selectedMessagingTimePeriod	= "";

	private VKCSearchQuery query = new VKCSearchQuery();

	//~ 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);

		messagingEnabled = false;

		selectedId 	= null;
		uniqueId 	= new Integer(0);
		
		queryIds	    	= new Integer[0];
		selectedCategoryIds	= new Integer[0];
		selectedSubDirIds	= new Integer[0];
		selectedDocumentIds	= new Integer[0];
		selectedQueryIds	= new Integer[0];
		
		editMode					= EDITMODE_MESSENGER;
		keywordsString				= "";
		selectedMessagingTimePeriod	= "";

		query = new VKCSearchQuery();
	}

	/**
	 * 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();
		
		setMessagingEnabled(request.getParameter("messagingEnabled") != null);
		
		synchronizeForm(request);

		if (request.getParameter("action.save.messenger") != null) {
			for (Iterator iter = getDynaKeys(); iter.hasNext();) {
				String keyId = (String)iter.next();

				if (keyId.startsWith("thresholdId_")) {
					try{
						Integer threshold = Integer.valueOf((String)getDynaValue(keyId));
						
						if (threshold.intValue() <= 0) {
							errors.add(keyId, new ActionError("vkc.messenger.error.threshold.greater.zero"));
						} else if (threshold.intValue() > 100) {
							errors.add(keyId, new ActionError("vkc.messenger.error.threshold.leq.hundred"));
						}
					} catch (NumberFormatException e) {
						errors.add(keyId, new ActionError("vkc.messenger.error.integer"));
					}
				}
			}
		}

		if (request.getParameter("action.save.searchquery") != null) {
			String from  = getQuery().getSearchForCreationDateFrom();
			String until = getQuery().getSearchForCreationDateUntil();
			Date f = null;
			Date u = null;
				
			if (!isEmpty(from)) {
				if ((f = DateUtils.parseDate(from)) == null) {
					errors.add("creationDateFrom", new ActionError("error.creation.date"));
					setEditMode(EDITMODE_SEARCHQUERY);
				}
			}

			if (!isEmpty(until)) {
				if ((u = DateUtils.parseDate(until)) == null) {
					errors.add("creationDateUntil", new ActionError("error.creation.date"));
					setEditMode(EDITMODE_SEARCHQUERY);
				}
			}
				
			if (f != null && u != null && f.after(u)) {
				errors.add("creationDate", new ActionError("error.date.range"));
				setEditMode(EDITMODE_SEARCHQUERY);
			}
			
			if (!Search.parseSearchQuerySyntax(getQuery().getSearchQuery())) {
				errors.add("searchQuerySyntax", new ActionError("error.query.syntax"));
				setEditMode(EDITMODE_SEARCHQUERY);
			}
		}
		
		return errors;
	}
	
	public void synchronizeForm(HttpServletRequest request) {
		try {
			if (init(request)) {
				initializeForm();
			}
		} catch (DBException e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
		}
	}

 	private boolean init(HttpServletRequest request) {
		return request.getParameter("initialize") != null;
	}

	private void initializeForm() throws DBException {
		VKCUser user = getUser();

		user.retrieveRegisteredCategories();
		user.retrieveRegisteredDocuments();
		user.retrieveRegisteredQueries();
		
		HashMap categories = user.getRegisteredCategories();
		HashMap documents = user.getRegisteredDocuments();
		HashMap queries = user.getRegisteredQueries();
		Iterator itCatKeySet = categories.keySet().iterator();
		Iterator itDocKeySet = documents.keySet().iterator();
		Iterator itQueryKeySet = queries.keySet().iterator();
		
		Integer[] selectedCategoryIds = {};
		Integer[] selectedSubDirIds = {};
		Integer[] selectedDocumentIds = {};
		Integer[] selectedQueryIds = {};
		
		ArrayList tmpCatIds = new ArrayList();
		ArrayList tmpSubCatIds = new ArrayList();
		ArrayList tmpDocIds = new ArrayList();
		ArrayList tmpQueryIds = new ArrayList();
		
		while ( itCatKeySet.hasNext() ) {
			Integer catId = (Integer) itCatKeySet.next();
            RegisteredCategory category = (RegisteredCategory)categories.get(catId);
			tmpCatIds.add(catId);
            setDynaValue("categorySubjectId_" + catId, category.getSubjectForNotification());
			
			if (category.getIncludeSubDirs().booleanValue()) {
				tmpSubCatIds.add(catId);
			}
		}
		
		while (itDocKeySet.hasNext()) {
			Integer docId = (Integer) itDocKeySet.next();
			tmpDocIds.add(docId);
            setDynaValue("documentSubjectId_" + docId, ((RegisteredDocument)documents.get(docId)).getSubjectForNotification());
			setDynaValue("thresholdId_" + docId.toString(), ((RegisteredDocument)documents.get(docId)).getThreshold());
		}

		while (itQueryKeySet.hasNext()) {
			Integer queryId = (Integer) itQueryKeySet.next();
			tmpQueryIds.add(queryId);
            VKCSearchQuery query = (VKCSearchQuery)queries.get(queryId);
            setDynaValue("querySubjectId_" + queryId, query.getSubjectForNotification());
			setDynaValue("queryId_" + queryId.toString(), query.getQuery());
		}

		selectedCategoryIds = (Integer[])tmpCatIds.toArray(selectedCategoryIds);
		selectedSubDirIds = (Integer[])tmpSubCatIds.toArray(selectedSubDirIds);
		selectedDocumentIds = (Integer[])tmpDocIds.toArray(selectedDocumentIds);
		selectedQueryIds = (Integer[])tmpQueryIds.toArray(selectedQueryIds);

		//Im Editierformular alle Selectionboxen auf Standartwerte setzen
		setSelectedCategoryIds(selectedCategoryIds);
		setSelectedSubDirIds(selectedSubDirIds);
		setSelectedDocumentIds(selectedDocumentIds);
		setSelectedQueryIds(selectedQueryIds);
		setQueryIds((Integer[])tmpQueryIds.toArray(new Integer[0]));
		setSelectedMessagingTimePeriod(user.getMessagingTimePeriod().toString());
		setMessagingEnabled(user.getMessagingEnabled());
		
		// Keywords sortieren für die Ausgabe
		ArrayList keywords = new ArrayList(user.getKeywords());
		KeywordsSortFactory.sort(keywords, KeywordsSortFactory.SORT_BY_TERM_UP);
		StringBuffer sb = new StringBuffer();
		
		for (Iterator iter = keywords.iterator(); iter.hasNext();) {
			VKCKeyword keyword = (VKCKeyword)iter.next();
			sb.append(keyword.getTerm());
			sb.append('\n');
		}		
		
		setKeywordsString(sb.toString().trim());

	}

	public String getEditMode() {
	    return editMode;
	}
	
	public String getKeywordsString() {
		return keywordsString;
	}

	public boolean isMessagingEnabled() {
		return messagingEnabled;
	}

    public VKCSearchQuery getQuery() {
        return query;
    }

    public Integer[] getQueryIds() {
        return queryIds;
    }
    
	public List getRegisteredQueries() {
	    List queries = new ArrayList();
	    
	    for (int i = 0; i < getQueryIds().length; i++) {
	        VKCSearchQuery q = new VKCSearchQuery();
	        q.setQuery( (String)getDynaValue("queryId_" + getQueryIds()[i]));
	        q.setQueryId(getQueryIds()[i]);
	        queries.add(q);
	    }
	    
	    return queries;
	}
    
    public Integer[] getSelectedCategoryIds() {
		return selectedCategoryIds;
	}

	public Integer[] getSelectedDocumentIds() {
		return selectedDocumentIds;
	}

	public Integer getSelectedId() {
	    return selectedId;
	}
	
	public String getSelectedMessagingTimePeriod() {
		return selectedMessagingTimePeriod;
	}

    public Integer[] getSelectedQueryIds() {
        return selectedQueryIds;
    }
    
	public Integer[] getSelectedSubDirIds() {
		return selectedSubDirIds;
	}

	public Integer getUniqueId() {
		return uniqueId;
	}

	public void setEditMode(String s) {
		editMode = s;
	}

	public void setKeywordsString(String s) {
		keywordsString = s;
	}

	public void setMessagingEnabled(boolean b) {
		messagingEnabled = b;
	}

    public void setQuery(VKCSearchQuery q) {
        query = q;
    }
    
    public void setQueryIds(Integer[] ids) {
        queryIds = ids;
    }

	public void setSelectedCategoryIds(Integer[] ids) {
		selectedCategoryIds = ids;
	}

	public void setSelectedDocumentIds(Integer[] ids) {
		selectedDocumentIds = ids;
	}

	public void setSelectedId(Integer i) {
	    selectedId = i;
	}
	
	public void setSelectedMessagingTimePeriod(String s) {
		selectedMessagingTimePeriod = s;
	}

    public void setSelectedQueryIds(Integer[] ids) {
        selectedQueryIds = ids;
    }

	public void setSelectedSubDirIds(Integer[] ids) {
		selectedSubDirIds = ids;
	}

	public void setUniqueId(Integer i) {
		uniqueId = i;
	}

}