/*
 * $Id: ShowBestsellerAction.java,v 1.16 2006/12/18 15:50:22 lawern Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ShowBestsellerAction.java,v $
 * Revision 1.16  2006/12/18 15:50:22  lawern
 * Korowas Änderungen überarbeitet.
 *
 * Revision 1.14  2006/09/29 21:10:06  marbobo
 * + Sucheoptimiert
 *
 * Revision 1.13  2006/09/21 13:08:27  marbobo
 * + Unnötige addAll-Methodenaufruf entfernt
 *
 * Revision 1.12  2005/08/10 23:38:45  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  2005/01/05 14:44:11  marbobo
 * + Nur Dokumente mit Zugriff > 0 anzeigen
 *
 * Revision 1.9  2004/11/10 15:02:44  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.8  2004/10/04 13:44:52  marbobo
 * + Überarbeitet
 *
 * Revision 1.7  2004/04/26 21:59:25  marbobo
 * + Dokumentsicht erweitert (mit/ohne Details)
 *
 * Revision 1.6  2004/03/07 13:45:45  bigmac
 * Anpassungen an VKCDocumentTypeSerializer, VKCDocumentClassSerializer, VKCDocumentStatusSerializer
 *
 * Revision 1.5  2003/12/24 10:11:52  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.4  2003/07/31 13:59:30  bigmac
 * Compilerwarnungen beseitigt
 *
 * Revision 1.3  2003/02/28 15:50:24  jonyp
 * use now showBestseller/LatestAdditons With param VKCUser
 *
 * Revision 1.3  2003/01/31 03:57:58  koppy
 * accessCounter bei Dokumenten + checkPermissionTag abstrahiert
 *
 * Revision 1.2  2003/01/24 03:48:58  koppy
 * document version feature
 *
 * Revision 1.1  2002/11/12 15:28:20  koppy
 * Initiale Version
 *
 */
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.ShowBestsellerForm;

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

    public ActionForward execute( ActionMapping mapping, 
    							  ActionForm f,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
    throws ServletException {
        try {
    		ShowBestsellerForm form = (ShowBestsellerForm)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(ShowBestsellerForm form, HttpServletRequest request) throws Exception {
		form.setCurrentResultPageId(new Integer(1));
		synchronizeForm(form, request);
        
		return DEFAULT_FORWARD_ANCHORRESULT;
    }

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

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

	private ActionForward handleHideDocumentDetailsAction(ShowBestsellerForm 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/ShowBestsellerTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

    private ActionForward handleShowDocumentDetailsAction(ShowBestsellerForm 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/ShowBestsellerTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleHideDocumentsAction(ShowBestsellerForm 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/ShowBestsellerTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleShowDocumentsAction(ShowBestsellerForm 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/ShowBestsellerTemplate.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleInitialzeAction(ShowBestsellerForm form, HttpServletRequest request) throws Exception {
		//Nachsehen ob in der Session Einstellungen für die Sortierung existiert
		if (request.getSession().getAttribute("bestsellerDocumentSortMode") == null) {
			//Wenn nicht werden die Einstellungen aus dem User-Objekt geholt
        	if (form.getUser() != null && form.getUser().getBestsellerDocumentSortMode() != null) {
            	request.getSession().setAttribute("bestsellerDocumentSortMode", form.getUser().getBestsellerDocumentSortMode());
        	    form.setDocumentSortMode(form.getUser().getBestsellerDocumentSortMode());
        	} else {
        	    form.setDocumentSortMode(new Integer(ShowBestsellerForm.DOCUMENT_SORT_ACCESSCOUNT_DOWN));
        	}
		} else {
    	    form.setDocumentSortMode((Integer)request.getSession().getAttribute("bestsellerDocumentSortMode"));
		}

		synchronizeForm(form, request);
		
		return DEFAULT_FORWARD_ANCHORRESULT;
	}

    private void synchronizeForm(ShowBestsellerForm 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("bestsellerDocumentSortMode", form.getDocumentSortMode());
    }
}