/*
 * $Id: ShowLatestAdditionsAction.java,v 1.17 2006/12/18 15:50:22 lawern Exp $
 * 
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ShowLatestAdditionsAction.java,v $
 * Revision 1.17  2006/12/18 15:50:22  lawern
 * Korowas Änderungen überarbeitet.
 *
 * Revision 1.15  2006/09/29 21:10:07  marbobo
 * + Sucheoptimiert
 *
 * Revision 1.14  2006/09/21 13:08:26  marbobo
 * + Unnötige addAll-Methodenaufruf entfernt
 *
 * Revision 1.13  2005/09/07 13:51:01  marbobo
 * + Sortierung nach Erstellungsdatum implementiert
 *
 * Revision 1.12  2005/08/12 00:09:22  marbobo
 * + Alternative-Sicht implementiert
 *
 * Revision 1.11  2005/05/02 15:24:50  marbobo
 * +Ergänzungen und Bugfixing bzgl. der Speicherung der Sortierungeinstellungen in der Session
 *
 * Revision 1.10  2004/11/10 15:02:45  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.9  2004/09/23 13:23:11  marbobo
 * + Performance speedup
 *
 * Revision 1.8  2004/09/22 23:26:49  marbobo
 * + einige neue Funktionen eingebaut
 *
 * Revision 1.7  2004/07/20 08:48:47  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.view.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.search.Hits;
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.misc.VKCLogManager;
import vkc.search.Search;
import vkc.search.SearchResultEntry;
import vkc.view.form.ShowLatestAdditionsForm;

/**
 * Action für die Ausgabe der Latest Additions
 *
 * @author koppy
 */
public final class ShowLatestAdditionsAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp");
	private ActionForward DEFAULT_FORWARD_ANCHORRESULT = new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp?anchor=results");

    public ActionForward execute( ActionMapping mapping, 
    							  ActionForm f,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
    throws ServletException {
        try {
    		ShowLatestAdditionsForm form = (ShowLatestAdditionsForm)f;
			
    		if (request.getParameter("action.change.page") != null) {
                return handleChangeCurrentPageAction(form, request);
            } else if (request.getParameter("action.change.category") != null) {
                return handleChangeCategoryAction(form, request);
            } else if (request.getParameter("action.show.document.details") != null) {
				return handleShowDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.hide.document.details") != null) {
				return handleHideDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.show.documents") != null) {
				return handleShowDocumentsAction(form, request);
			} else if (request.getParameter("action.hide.documents") != null) {
				return handleHideDocumentsAction(form, request);
			} else if (request.getParameter("action.reload.documents") != null) {
				return handleReloadDocumentsAction(form, request);
			} else {
				return handleInitialzeAction(form, request);
			}
        } catch (Exception ex) {
            VKCLogManager.errorLog(this, "", ex.getMessage(),ex);
            throw new ServletException(ex);
        }
    }

    private ActionForward handleReloadDocumentsAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		form.setCurrentResultPageId(new Integer(1));
        synchronizeForm(form, request);
        
		return DEFAULT_FORWARD_ANCHORRESULT;
    }

    private ActionForward handleChangeCurrentPageAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		synchronizeForm(form, request);
        
		return DEFAULT_FORWARD_ANCHORRESULT;
    }

    private ActionForward handleChangeCategoryAction(ShowLatestAdditionsForm form, HttpServletRequest request) {
        return DEFAULT_FORWARD;
    }

	private ActionForward handleHideDocumentDetailsAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.remove(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

    private ActionForward handleShowDocumentDetailsAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.add(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));
		synchronizeForm(form, request);

		return new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleHideDocumentsAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocuments()));
		ids.remove(form.getSelectedId());
		form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
		synchronizeForm(form, request);
		
		return new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleShowDocumentsAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		List ids = new ArrayList(Arrays.asList(form.getShowDocuments()));
		ids.add(form.getSelectedId());
		form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
		synchronizeForm(form, request);

		return new ActionForward("/templates/${template.name}/common/ShowLatestAdditionsTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleInitialzeAction(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		//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 (form.getUser() != null && form.getUser().getLatestAdditionsDocumentSortMode() != null) {
            	request.getSession().setAttribute("latestAdditionsDocumentSortMode", form.getUser().getLatestAdditionsDocumentSortMode());
        	    form.setDocumentSortMode(form.getUser().getLatestAdditionsDocumentSortMode());
        	} else {
            	form.setDocumentSortMode(new Integer(ShowLatestAdditionsForm.DOCUMENT_SORT_PUBLISHING_DATE_DOWN));
        	}
		} else {
        	form.setDocumentSortMode((Integer)request.getSession().getAttribute("latestAdditionsDocumentSortMode"));
		}

		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD_ANCHORRESULT;
	}

    private void synchronizeForm(ShowLatestAdditionsForm form, HttpServletRequest request) throws Exception {
		Hits hits = form.getHits();
		int hitsSize = hits != null ? hits.length() : 0;
	    
		Integer resultsPerPage = new Integer(form.getSelectedNumberOfResultsPerPage());
		Integer currentPageId = form.getCurrentResultPageId();
	    int startIndex = resultsPerPage.intValue() * ((currentPageId.intValue() > 1) ? (currentPageId.intValue() - 1) : 0);
		int endIndex = startIndex + resultsPerPage.intValue();

		form.setHitsCount(new Integer(hitsSize));
		form.setStartIndex(new Integer(startIndex));
			
		if (hitsSize < endIndex) {
			endIndex = hitsSize;
		}
			
		List results = new ArrayList();
			
		for (int i = startIndex; i < endIndex; i++) {
			results.add(SearchResultEntry.toSearchResultEntry(hits.doc(i), hits.score(i)));
		}
		Search.searchFinished();
        
	    //Anzahl der Ergebnisseiten ermitteln
	    Integer pageCount = new Integer(((form.getHitsCount().intValue() % resultsPerPage.intValue()) == 0)
	              					    ? (form.getHitsCount().intValue() / resultsPerPage.intValue())
	                                    : ((form.getHitsCount().intValue() / resultsPerPage.intValue()) + 1));

	    form.setPageCount(pageCount);
	    form.setResults(results);
	    
    	//Einstellungen für die Sortierung in der Session speichern
        request.getSession().setAttribute("latestAdditionsDocumentSortMode", form.getDocumentSortMode());
   }
}