/*
 * Created on 23 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.File;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpURL;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.webdav.lib.WebdavFile;
import org.injac.indexing.exceptions.ConnectionException;
import org.injac.indexing.index.GenericIndexingServlet;
import org.injac.indexing.util.FileTools;
import org.injac.indexing.util.WebdavConnection;


/**
 * Classe permettant de faire l'indexation d'un seul 
 * fichier WebDav, a condition que ce soit publie inJac
 * @author marius
 */
public class SimpleIndexingServlet extends GenericIndexingServlet {
	
	private ResourceBundle resBundle;
	
	public SimpleIndexingServlet() {
		super();
		resBundle = ResourceBundle.getBundle("indexation");
	}
	public void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, java.io.IOException {
		
		String url = request.getParameter("url");
		String user = request.getParameter("user");
		String password = request.getParameter("pass");
		String indexName = request.getParameter("name");
		String indexPath = resBundle.getString("indexPath");
		String contextPath = getServletContext().getRealPath("/");
		String mode = request.getParameter("mode");
		int mdMode= extractMode(mode);
		HttpSession session = request.getSession();
		WebdavConnection webdavConnection = new WebdavConnection(session);
		java.io.PrintWriter writer = response.getWriter();
		writer.println("<head><title>Indexation</title></head>");
		writer.println("<body>");		
		
		FileTools dc = new FileTools();
		File index = new File(indexPath + "/"+ indexName);
		
		if(!index.exists()){
			writer.println("<p>Error: index "+indexName+" not created yet ! " + 
					"Please create index first and try again.'/p>");
			}
		else if(!exists(index,url)){		
				File temp = new File(indexPath + "/Temp");
				temp.mkdir();
		
				try{
					HttpURL hrl = new HttpURL(url);
					hrl.setUserinfo(user, password);
					WebdavFile wf = new WebdavFile(hrl);
					logger.debug("Adding " + url + " to index...");
					InjacIndexing indexare = new InjacIndexing(indexName,contextPath,mdMode, webdavConnection);
					indexare.index(wf, indexName);
					logger.debug("File added to index!");
					writer.println("<p>File " + url + 
					" added to index</p>");
					}
				catch(HttpException he)
				{
					logger.error("HttpException");
					writer.println("HttpException<br>");
				}
				catch(IOException ioe)
				{
					logger.error("IOException");
					writer.println("IOException<br>");
				}
				catch(ConnectionException ce){
		        	writer.println("Resource doesn't exist, " + 
		        			"or wrong credentials.<br>");
		        }
		        catch(NullPointerException npe){
		        	writer.println("Resource doesn't exist, " + 
		        			"or wrong credentials.<br>");
		        }
        
				dc.eraseDir(temp);
				
					
				}
				else{
					writer.println("<p>File " + 
							url + " already indexed!" + 
							" Please add another file...</p>");
					writer.println("<form method=\"GET\"");
					writer.println("action=\"servletIndexationSimple\">");
					writer.println("<p>url (a indexer): <input type=\"text\" name=\"url\" /></p>");
					writer.println("<p>utilisateur:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					writer.println("<input type=\"text\" name=\"user\" /></p>");
					writer.println("<p>mot de passe:&nbsp;");
					writer.println("<input type=\"password\" name=\"pass\" /></p>");
					writer.println("<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					writer.println("<input type=\"submit\" value=\"indexer\" />");
					writer.println("&nbsp;<input type=\"reset\" value=\"Effacer\" /></p>");
					writer.println("</form>");
					}
		
		
		writer.println("</body></html>");
		writer.close();
	}
	/**
	 * Teste s'il existe dans l'index un fichier avec 
	 * le champ url contenu dans le parametre url
	 * @param indexDir
	 * @param url
	 * @return boolean
	 */
	private boolean exists(File indexDir, String url){
		try{
			IndexReader reader = IndexReader.open(indexDir);
			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("name");
					adress = adress + "/" + name;
					if(adress.equals(url)){
						reader.close();
						return true;
						}
					}
				else{
					n++;
					}
				}
			reader.close();
			}
		
		catch(IOException ioe){
			ioe.printStackTrace();
			}
		
		return false;
		}
}
