/*
 * 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 org.injac.indexing.util.PathManager;
import org.injac.indexing.Consts;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.servlet.http.*;
import javax.servlet.ServletException;

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;



/**
 * Classe de recherche simple avec réponse XML
 * @author François Jannin
 */
public class SearchServlet extends GenericSearchServlet {
	
	static Logger logger = Logger.getLogger(SearchServlet.class);
	
	
	public SearchServlet(){
		super();
		resBundle = ResourceBundle.getBundle("indexation");
		
	}
	/**
	 * Primitives implementation
	 */
	
	protected PrintWriter startResponse(String query, HttpServletResponse response){
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter writer= null;
		try{
			writer= response.getWriter();
			writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			writer.println("<results>");
			writer.println("<query><![CDATA["+query+"]]></query>");
			
		}catch(Exception e){
			logger.error(e.getLocalizedMessage());
		}
		return writer;
	}
	protected void endResponse(PrintWriter writer){
		writer.println("</results>");
		writer.close();
	}
	/**
	 * do stuff to build resutls in response
	 */
	protected void doSearch(String query, PrintWriter writer)
			throws ServletException, IOException {
		try{
			search(index, query, writer);
		}
		catch(Exception e){
				writer.println("<msg>Error : "+e.getLocalizedMessage()+"</msg>");
		}
	}
	protected void errorMsg(HttpServletRequest request,
			PrintWriter writer) {
		writer.println("<msg>ERROR : "+errorMsg+"</msg>");
	}
	
	
	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());
	    
	    QueryParser qparser = new QueryParser("body", new StandardAnalyzer());
	    
	    Query query = qparser.parse(q);
	    Hits hits = is.search(query);
	    // return number of hits only
	    if(hitsOnly){
	    	writer.println("<hits found=\""+hits.length() +"\" />");
	    	is.close();
	    	return;
	    }
	    writer.println("<hits found=\""+hits.length() +"\" >") ;
	    
	    for (int i = 0; i < hits.length(); i++) {
	        Document doc = hits.doc(i);
	        int score = Math.round(hits.score(i)*100);
	        String title= doc.get(Consts.INDEX_TITLE);
	        String filename = doc.get("name");
	        String url= processURL(getRenderURL(doc.get("url"),filename));
	        writer.println("<hit title=\""+title+"\" href=\""+url+"\" score=\"" + score+"\" filename=\""+ filename + "\">");
	        
	        ArrayList resultFields = getResultFields(doc);
	        if(resultFields.size()>0){
	        	writer.println("<metadatas>");
	        	for(int j=0;j<resultFields.size();j++){
		        	Field field = (Field)resultFields.get(j);
		        	String value= field.stringValue();
	    			String fieldname = field.name();
		        	writer.println("<metadata name=\""+fieldname+"\" value=\""+value+"\" />");
		        }
	        	writer.println("</metadatas>");
	        }
	        
	      
	        writer.println("</hit>");
	    }
	    writer.println("</hits>");
	    is.close();
	   
	}
	
	

}
