/*
 * Created on 26 mai 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.injac.indexing.search;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.httpclient.util.URIUtil;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.document.Field;
import org.injac.indexing.Consts;
import org.injac.indexing.util.FileTools;


/**
 * Classe de recherche simple - affichage html 
 * @author marius
 */
public class HtmlSearchServlet extends GenericSearchServlet {
	
	static Logger logger = Logger.getLogger(HtmlSearchServlet.class);
	private String cssfile;
	
	public HtmlSearchServlet(){
		super();
		resBundle = ResourceBundle.getBundle("indexation");
		cssfile = resBundle.getString("cssFile");
		
	}
	
	protected PrintWriter startResponse(String query, HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer= null;
		try{
			writer= response.getWriter();
			writer.println("<html><head>");
			writer.println("<link href=\""+cssfile+"\" rel=\"stylesheet\" type=\"text/css\">");
			writer.println("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
			writer.println("<title>Resultat recherche</title></head><body>");
			writer.println("<div id=\"iDocRender\">");
			writer.println("<h2>Resultat de la recherche</h2>");
		}catch(Exception e){
			logger.error(e.getLocalizedMessage());
		}
		return writer;
	}
	protected void endResponse(PrintWriter writer){
		writer.println("</div</body></html>");
		writer.close();
	}
	/**
	 * do stuff to build results in response
	 */
	public void doSearch(String query, PrintWriter writer)
			throws ServletException, IOException {
		try{
			search(index, query, writer);
		}
		catch(Exception e){
			writer.println("<p>Error : "+e+e.getLocalizedMessage()+"</p>");
		}
	}
	protected void errorMsg(HttpServletRequest request,
			PrintWriter writer) {
		writer.println("<p>Error : "+errorMsg+"</p>");
	}
	
	
	public void search(File indexDir, String q, java.io.PrintWriter writer)  throws Exception{
	    Directory fsDir = FSDirectory.getDirectory(indexDir, false);
	    IndexSearcher is = new IndexSearcher(fsDir);

	    Query query = QueryParser.parse(q, "body", new StandardAnalyzer());
	    Hits hits = is.search(query);
	    writer.println("<h3>"+hits.length()+" document(s) trouvé(s) pour la requête "+q+"</h3>");
	    writer.println("<ul class=\"idocs\">");
	    
	    for (int i = 0; i < hits.length(); i++) {
	        Document doc = hits.doc(i);
	        String title= doc.get(Consts.INDEX_TITLE);
	        // modif exist
	        String filename = getDocName(doc);
	        String url= getRenderURL(doc);
	        
	        //String filename = doc.get("name");
	        //String url= processURL(getRenderURL(doc.get("url"),filename));
	        
	        int score = Math.round(hits.score(i)*100);
	        writer.println("<li>"); 
	        		
	        writer.println("<a href=\"" +
					url + "\">" + 
			title + " (score : "+score+"%)</a>");
	        
	       
	        ArrayList resultFields = getResultFields(doc);
	        for(int j=0;j<resultFields.size();j++){
	        	Field field = (Field)resultFields.get(j);
	        	writer.println("<p>"+field.name()+" : "+field.stringValue()+"</p>");
	        }
	       
	        
	        writer.println("</li>");
	        
	    }
	    writer.println("</ul>");
	    is.close();
	}
	
	
}
