/*
 * $Id: ShowLatestAdditionsForm.java,v 1.20 2006/12/18 15:50:23 lawern Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ShowLatestAdditionsForm.java,v $
 * Revision 1.20  2006/12/18 15:50:23  lawern
 * Korowas Änderungen überarbeitet.
 *
 * Revision 1.18  2006/09/29 21:10:09  marbobo
 * + Sucheoptimiert
 *
 * Revision 1.17  2005/09/15 00:48:10  marbobo
 * + Sprachabhängiges Sortieren implementiert
 *
 * Revision 1.16  2005/09/07 13:51:01  marbobo
 * + Sortierung nach Erstellungsdatum implementiert
 *
 * Revision 1.15  2005/09/05 13:52:48  marbobo
 * + Refactoring (Methode umbenannt)
 *
 * Revision 1.14  2005/08/12 00:09:22  marbobo
 * + Alternative-Sicht implementiert
 *
 * Revision 1.13  2005/05/02 15:24:50  marbobo
 * +Ergänzungen und Bugfixing bzgl. der Speicherung der Sortierungeinstellungen in der Session
 *
 * Revision 1.12  2005/04/29 10:50:54  korowa
 * Die gespeicherte im Datenbank Sortierungsarten werden jetzt am Anfang jeder Sitzung
 * geladen und aktiviert.
 *
 * Revision 1.11  2005/04/21 14:06:28  korowa
 * Die Sortierungart von Dokumenten in Dokumentablage, Bestseller und Neuerscheinungen
 * und Die Sortierungart von Kategorien in Dokumentablage bleibt jetzt während der ganzen
 * Sitzung aktuell.
 *
 * Revision 1.10  2005/02/15 09:26:52  bigmac
 * Refactorings
 *
 * Revision 1.9  2004/11/09 14:35:36  marbobo
 * + Umstellung von authorId auf publisherId
 * + Hinzufügen von AuthorName für Dokumente
 * + Nötwendige Änderungen betreffend AuthorName und PublisherId
 *
 * Revision 1.8  2004/09/23 13:23:11  marbobo
 * + Performance speedup
 *
 * Revision 1.7  2004/09/22 23:26:50  marbobo
 * + einige neue Funktionen eingebaut
 *
 * Revision 1.6  2004/09/22 13:11:06  marbobo
 * + Vorbereitungen für einige neue Funktionen
 *
 * Revision 1.5  2004/07/20 08:55:41  jonyp
 * added copyright info + cvs log
 *
 *
 */

package vkc.view.form;

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 org.apache.lucene.search.Hits;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

import vkc.db.entities.VKCCategory;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.exception.DBException;
import vkc.search.Search;
import vkc.util.DateUtils;
import vkc.util.StringUtils;
import vkc.util.VKCCategoryAbsPath;
import vkc.view.WebShare;
import vkc.view.bean.CategorySettings;

public final class ShowLatestAdditionsForm extends BasicActionForm {
	public final static int DOCUMENT_SORT_PUBLISHING_DATE_UP   	= 1;
	public final static int DOCUMENT_SORT_PUBLISHING_DATE_DOWN 	= 2;

	public final static int DOCUMENT_SORT_TITLE_UP  			= 3;
	public final static int DOCUMENT_SORT_TITLE_DOWN			= 4;

	public final static int DOCUMENT_SORT_AUTHOR_UP 			= 5;
	public final static int DOCUMENT_SORT_AUTHOR_DOWN			= 6;
	
	public final static int DOCUMENT_SORT_SIZE_UP  				= 7;
	public final static int DOCUMENT_SORT_SIZE_DOWN 			= 8;

	public final static int DOCUMENT_SORT_TYPE_UP  				= 9;
	public final static int DOCUMENT_SORT_TYPE_DOWN 			= 10;

	public final static int DOCUMENT_SORT_PUBLISHER_UP 			= 13;
	public final static int DOCUMENT_SORT_PUBLISHER_DOWN		= 14;

	public final static int DOCUMENT_SORT_CREATION_DATE_UP   	= 15;
	public final static int DOCUMENT_SORT_CREATION_DATE_DOWN 	= 16;

	private Integer currentResultPageId	= new Integer(1);
	private Integer documentSortMode 	= new Integer(DOCUMENT_SORT_PUBLISHING_DATE_DOWN);
	private Integer hitsCount			= new Integer(0);
	private Integer pageCount			= new Integer(1);
	private Integer startIndex			= new Integer(0);
	private Integer selectedId 			= null;

	private Integer[] showDocumentDetails = new Integer[0];
	private Integer[] showDocuments = new Integer[0];

    private List results	= new ArrayList(); 
    
	private String selectedCategoryId				= String.valueOf(VKCCategory.ROOT_CATEGORY_ID);
	private String selectedNumberOfResultsPerPage	= "5";
	private String validFrom						= "";
	private String validUntil						= "";

	/**
	 * Reset all properties to their default values.
	 *
	 * @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);

		currentResultPageId	= new Integer(1);
		
		hitsCount			= new Integer(0);
		pageCount			= new Integer(1);
		startIndex			= new Integer(0);
		selectedId 			= null;

		showDocumentDetails = new Integer[0];
		showDocuments = new Integer[0];

	    results		= new ArrayList(); 
	    
		selectedCategoryId				= String.valueOf(VKCCategory.ROOT_CATEGORY_ID);
		selectedNumberOfResultsPerPage	= "10";
		validFrom						= "";
		validUntil						= "";

		//Nachsehen ob in der Session Einstellungen für die Sortierung existiert
		if (request.getSession().getAttribute("latestAdditionsDocumentSortMode") == null) {
			//Wenn nicht werden die Einstellungen aus dem User-Objekt geholt
        	if (getUser() != null && getUser().getLatestAdditionsDocumentSortMode() != null) {
            	request.getSession().setAttribute("latestAdditionsDocumentSortMode", getUser().getLatestAdditionsDocumentSortMode());
        	    documentSortMode = getUser().getLatestAdditionsDocumentSortMode();
        	} else {
        		documentSortMode 	= new Integer(DOCUMENT_SORT_PUBLISHING_DATE_DOWN);
        	}
		} else {
        	documentSortMode = (Integer)request.getSession().getAttribute("latestAdditionsDocumentSortMode");
		}
	}	
		
	/**
	 * 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("initialize") != null) {
		    Date d = new Date(System.currentTimeMillis());

		    setValidUntil(DateUtils.getDD_MM_YYYY(d));
			
		    Calendar c = Calendar.getInstance();
			c.setTime(d);
			c.add(Calendar.MONTH, -1);
			
			setValidFrom(DateUtils.getDD_MM_YYYY(c.getTime()));
		}
		
		if (request.getParameter("action.reload.documents") != null) {		
			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"));
			}
		}

		return errors;
	}

	public List getResults() {
		return results;
	}

    public void setResults(List l) {
		results = l;
	}

	public CategorySettings getCategorySettings() {
		return WebShare.getCategorySettings();
	}

	public Integer[] getShowDocuments() {
		return showDocuments;
	}

	public void setShowDocuments(Integer[] list) {
		showDocuments = list;
	}

	public boolean getShowDocs(int i) {
		List ids = Arrays.asList(getShowDocuments());

		return ids.contains(new Integer(i));
	}

	public Integer[] getShowDocumentDetails() {
		return showDocumentDetails;
	}

	public void setShowDocumentDetails(Integer[] list) {
		showDocumentDetails = list;
	}

	public boolean getShowDocDetails(int i ) {
		List ids = Arrays.asList(getShowDocumentDetails());
		
		return ids.contains(new Integer(i));
	}

	public Integer getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(Integer integer) {
		selectedId = integer;
	}

	public String getSelectedCategoryId() {
	    return selectedCategoryId;
	}
	
	public String getValidFrom() {
		return validFrom;
	}

	public String getValidUntil() {
		return validUntil;
	}

	public Date getFrom() {
		if (isEmpty(getValidFrom())) {
			return null;
		} 

		Date d = DateUtils.parseDate(getValidFrom());
		
		return d;
	}

	public Date getUntil() {
		if (isEmpty(getValidUntil())) {
			return null;
		} 
		
		Date d = DateUtils.parseDate(getValidUntil());
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.set(Calendar.HOUR_OF_DAY, 23);
		c.set(Calendar.MINUTE, 59);
		c.set(Calendar.SECOND, 59);
		
		return c.getTime();
	}

	public void setSelectedCategoryId(String s) {
		selectedCategoryId = StringUtils.normalize(s);
	}

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

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

    public void setCurrentResultPageId(Integer id) {
        currentResultPageId = id;
    }

    public Integer getCurrentResultPageId() {
        return currentResultPageId;
    }

	public Integer getNextPageId() {
		return new Integer(getCurrentResultPageId().intValue() + 1);
	}

	public Integer getPreviousPageId() {
		return new Integer(getCurrentResultPageId().intValue() - 1);
	}

	public Integer getHitsCount() {
		return hitsCount;
	}

	public void setHitsCount(Integer i) {
		hitsCount = i;
	}

	public Integer getPageCount() {
		return pageCount;
	}

	public void setPageCount(Integer i) {
		pageCount = i;
	}
	
	public Integer[] getPagesIndex() {
		Integer resultsPerPage = new Integer(getSelectedNumberOfResultsPerPage());
		Integer pagesCount = new Integer(((getHitsCount().intValue() % resultsPerPage.intValue()) == 0)
										? (getHitsCount().intValue() / resultsPerPage.intValue())
										: ((getHitsCount().intValue() / resultsPerPage.intValue()) + 1));
		Integer[] pagesIndex = new Integer[pagesCount.intValue()];

		for (int i = 0; i < pagesIndex.length; i++) {
			pagesIndex[i] = new Integer(i + 1);
		}
		
		return pagesIndex;
	}
	
    public String getSelectedNumberOfResultsPerPage() {
        return selectedNumberOfResultsPerPage;
    }

    public void setSelectedNumberOfResultsPerPage(String s) {
        selectedNumberOfResultsPerPage = StringUtils.normalize(s);
    }

	public Integer getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(Integer integer) {
		startIndex = integer;
	}
	
    public String getCategoryPath() {
        VKCCategoryAbsPath cap = null;
        Integer categoryId = null;
        
        categoryId = Integer.valueOf(getSelectedCategoryId());
        
        try {
            cap = VKCCategorySerializer.getCategoryAbsPath(categoryId);
        } catch (DBException e) {
            cap = new VKCCategoryAbsPath();
        }
        
        return cap.getAbsolutePathString();
    }

	public Integer getDocumentSortMode() {
	    return documentSortMode;
	   
	}

	public void setDocumentSortMode(Integer i) {
	    documentSortMode = i;
	}

	public Hits getHits() {
		Integer searchCategoryId = (Integer.parseInt(getSelectedCategoryId()) == VKCCategory.ROOT_CATEGORY_ID) 
									? null 
							        : Integer.valueOf(getSelectedCategoryId());
		Hits hits = null;
		Sort sort = null;
		int mode = getDocumentSortMode().intValue();

		switch (mode) {
			case DOCUMENT_SORT_PUBLISHING_DATE_UP:
				sort = new Sort(new SortField("published", SortField.STRING));
				break;
			case DOCUMENT_SORT_PUBLISHING_DATE_DOWN: 
				sort = new Sort(new SortField("published", SortField.STRING, true));
				break;
			case DOCUMENT_SORT_CREATION_DATE_UP: 
				sort = new Sort(new SortField("creationDate", SortField.STRING));
				break;
			case DOCUMENT_SORT_CREATION_DATE_DOWN: 
				sort = new Sort(new SortField("creationDate", SortField.STRING, true));
				break;
			case DOCUMENT_SORT_TITLE_UP: 
				sort = new Sort(new SortField("title_sort", getUser().getLanguage().getLocale()));
				break;
			case DOCUMENT_SORT_TITLE_DOWN: 
				sort = new Sort(new SortField("title_sort", getUser().getLanguage().getLocale(), true));
				break;
			case DOCUMENT_SORT_AUTHOR_UP: 
				sort = new Sort(new SortField("authorname_sort", getUser().getLanguage().getLocale()));
				break;
			case DOCUMENT_SORT_AUTHOR_DOWN: 
				sort = new Sort(new SortField("authorname_sort", getUser().getLanguage().getLocale(), true));
				break;
			case DOCUMENT_SORT_PUBLISHER_UP: 
				sort = new Sort(new SortField("publishername_sort", getUser().getLanguage().getLocale()));
				break;
			case DOCUMENT_SORT_PUBLISHER_DOWN: 
				sort = new Sort(new SortField("publishername_sort", getUser().getLanguage().getLocale(), true));
				break;
			case DOCUMENT_SORT_SIZE_UP: 
				sort = new Sort(new SortField("docSize", SortField.STRING));
				break;
			case DOCUMENT_SORT_SIZE_DOWN: 
				sort = new Sort(new SortField("docSize", SortField.STRING, true));
				break;
			case DOCUMENT_SORT_TYPE_UP: 
				sort = new Sort(new SortField("docTypeName", getUser().getLanguage().getLocale()));
				break;
			case DOCUMENT_SORT_TYPE_DOWN: 
				sort = new Sort(new SortField("docTypeName", getUser().getLanguage().getLocale(), true));
				break;
		}
		
		hits = Search.search("docClassId:(classid*)", getFrom(), getUntil(), 
				 "*", getUser(), searchCategoryId, null, null, sort);

		return hits;
	}
}