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

import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.GenericServlet;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;

import org.injac.indexing.beans.*;

/**
 * Classe permettant d'afficher dans une page web
 * les noms complets (url) de tous les fichiers dans
 * l'index
 * @author marius
 */
public class ListIndex extends HttpServlet {
	static Logger logger = Logger.getLogger("INJAC_INDEX");
	private ResourceBundle resBundle;
	private String indexPath;
	public ListIndex() {
		super();
		resBundle = ResourceBundle.getBundle("indexation");
	}
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		javax.servlet.ServletContext context =getServletContext();
		IndexListBean indexListBean = (IndexListBean)context.getAttribute("indexListBean");
		indexPath=resBundle.getString("indexPath");
		
		int index = -1;
		String indexS = request.getParameter("index");
		index = Integer.parseInt(indexS);
		
		java.io.PrintWriter writer = response.getWriter();
		
		
	
		String indexName = indexListBean.getName(index);
		File indexFile = new File(indexPath + "/"+ indexName);
		if(!indexFile.exists()){
			writer.println("<p>Error: index not created yet ! " + 
					"Please create index first and try again.'/p>");
			}
		else{
			writer.println("<p>");
			show(indexFile, writer);
			writer.println("</p>");
			}
		
		writer.close();
	}
	/**
	 * Fonction qui ecrit dans le PrintWriter writer
	 * les noms des fichiers de l'index indexDir
	 * @param indexDir
	 * @param writer
	 */
	private void show(File indexDir, java.io.PrintWriter writer){
		
		try{
			IndexReader reader = IndexReader.open(indexDir);
			String adress = null;
			String name = null;
			int n = reader.numDocs();
			writer.println("<h2>Liste des documents indexés</h2>");
			writer.println("<ul class=\"list\">");
			for(int i = 0 ;i < n ;i++){
				if(!reader.isDeleted(i)){
					Document d = reader.document(i);
					adress = d.get("url");
					name = d.get("name");
					adress = adress + "/" + name;
					writer.println("<li>"+adress+"</li>");
					}
				else{
					n++;
					}
				}
			writer.println("</ul>");
			reader.close();
			}
		
		catch(IOException ioe){
			ioe.printStackTrace();
			}
		}
}
