/*
 * 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.index.webdav;

import java.io.IOException;
import java.io.File;

//import java.util.Enumeration;

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

import org.apache.lucene.document.Document;
//import org.apache.lucene.index.SegmentReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.injac.indexing.util.FileTools;


/**
 * Classe permettant d'effacer un fichier de l'index
 * @author marius
 */
public class Erase extends GenericServlet {

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		
		String url = request.getParameter("url");
		
		java.io.PrintWriter writer = response.getWriter();
		writer.println("<head><title>Supprimation</title></head>");
		writer.println("<body>");
		
		FileTools dc = new FileTools();
		File index = new File(dc.getParent() + 
				"/webapps/proiectTomcat/indexSaroumane");
		if(!index.exists()){
			writer.println("<p>Error: l'index n'est pas " + 
					"encore créé. Veuillez créer l'index et puis " + 
					"essayer de nouveau!</p>");
			}
		else{
			boolean deleted = delete(index, url);
			if(deleted){
				writer.println("<p>Le fichier a été effacé" + 
						" avec succès!</p>" );
				}
			else{
				writer.println("<p>Fichier inexistent!" + 
						" Veuillez essayer de nouveau...</p>");
				}
			}
		writer.println("</body></html>");
		writer.close();
	}
	
	private boolean delete(File indexDir, String url){
		try{
			Directory directory = FSDirectory.getDirectory(indexDir, false);
			IndexReader reader = IndexReader.open(directory);
			String adress = null;
			String name = null;
			int n = reader.numDocs();
			for(int i = 0 ;i < n ;i++){
				if(!reader.isDeleted(i)){
					Document d = reader.document(i);
					adress = d.get("url");
					name = d.get("nume");
					adress = adress + "/" + name;
					if(adress.equals(url)){
						//Enumeration e = d.fields();
						reader.delete(i);
						reader.close();
						directory.close();
						return true;
						}
					}
				else{
					n++;
					}
				}
			reader.close();
			directory.close();
			}
		
		catch(IOException ioe){
			ioe.printStackTrace();
			}
		
		return false;
		}
	
}

