/*
 * 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 org.jdom.Attribute;
import org.jdom.output.XMLOutputter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
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;

import ca.ulaval.bibl.lius.search.*;

/**
 * Classe de recherche simple avec réponse XML
 * @author François Jannin
 */
public class LiusSearchServlet extends GenericSearchServlet {
	
	static Logger logger = Logger.getLogger(LiusSearchServlet.class);
	
	
	public LiusSearchServlet(){
		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();
		
			
		}catch(Exception e){
			logger.error(e+" : "+e.getLocalizedMessage());
		}
		return writer;
	}
	protected void endResponse(PrintWriter writer){
		
		writer.close();
	}
	/**
	 * do stuff to build resutls in response
	 */
	protected void doSearch(String query, PrintWriter writer)
			throws ServletException, IOException {
		
			search(index, query, writer);
		
		
	}
	protected void errorMsg(HttpServletRequest request,
			PrintWriter writer) {
		String query = request.getParameter("query");
		writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		writer.println("<results query=\""+query+"\" >");
		writer.println("<msg><![CDATA[ERROR : "+errorMsg+"]]></msg>");
		writer.println("</results>");
	}
	
	
	public void search(File indexDir, String q, java.io.PrintWriter writer)  throws ServletException, IOException{
	   
		SearchIndex searchingIndex = new SearchIndex();
		String liusConfigFile = resBundle.getString("liusConfigFile");
		org.jdom.Document doc = searchingIndex.searchResultAsJdomDoc(q, indexDir.getAbsolutePath(), liusConfigFile); 
		
		doc.getRootElement().getAttributes().add(new Attribute("query",q));
		
		XMLOutputter xop = new XMLOutputter();
	    try {
	      xop.output(doc, writer);
	    }
	    catch (IOException ex) {
	      ex.printStackTrace();
	    }
	    writer.close();
	    
	}
	
	

}
