/*
 * Created on 20 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 org.injac.indexing.beans.*;
import org.injac.indexing.util.WebdavConnection;
import java.io.File;
import java.io.IOException;

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

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpURL;
import org.apache.webdav.lib.WebdavFile;
import org.injac.indexing.exceptions.ConnectionException;
import org.injac.indexing.util.*;

import java.util.Date;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.injac.indexing.index.GenericIndexingServlet;
/**
 * Classe effectuant l'indexation d'une arborescence de repertoires
 * WebDav, sous reserve que l'espace racine soit de type inJac
 * 
 * @author Marius Mirea, François Jannin
 */
public class IndexingServlet extends GenericIndexingServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 944029745798300027L;
	private ResourceBundle resBundle;
	private String path;
	public IndexingServlet() {
		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 mode = request.getParameter("mode");
		int mdMode= extractMode(mode);
		int newIndex = 0;
		int docCount=0;	
		HttpSession session = request.getSession();
		
		indexPath= resBundle.getString("indexPath");
		path = request.getRequestURL().toString();
		path = path.substring(0,path.lastIndexOf('/'));
		
		
		
		WebdavConnection webdavConnection = new WebdavConnection(session);
		try{
			webdavConnection.connect(url, user, password);
		}catch(Exception e){
			sendError("unable to connect to "+url, path, response);	
			return;
		}
		
		
		//	test index name and update application bean indexListBean 
		newIndex = saveBean(response, session,indexName,url,user,password,mdMode);
		if(newIndex==-1){
			sendError("can't access indexListBean : redirecting to main page", path, response);
			return;
		}
			
		java.io.PrintWriter writer = response.getWriter();
		java.util.Date date = new java.util.Date();
		long begin = date.getTime();
		// create directories and report file
		File temp = createFiles(indexName, true);	
						
		try {
			HttpURL hrl = new HttpURL(url);
			hrl.setUserinfo(user, password);
			WebdavFile wf = new WebdavFile(hrl);
			String contextPath = getServletContext().getRealPath("/");
			logger.debug("REALPATH : "+contextPath);
			CreateBrowser apa = new CreateBrowser(contextPath, webdavConnection);
			docCount = apa.indexAll(wf,indexName,mdMode);

			logger.info("\nFound " + apa.getFileCount()
					+ " files " + "and " + apa.getDirectoryCount()
					+ " directories!");
			
		}

		catch (HttpException he) {
			logger.error("HttpException : "+he.getLocalizedMessage());
			writer.println("HttpException<br>");
		} catch (IOException ioe) {
			logger.error("IOException: " + ioe.getLocalizedMessage());
			writer.println("IOException<br>");
		} catch (ConnectionException ce) {
			logger.error("ConnectionException :"+ce.getLocalizedMessage());
			writer.println("Resource doesn't exist or credentials are wrong");
		} catch (NullPointerException npe) {
			logger.error("NullPointerException : "+npe.getLocalizedMessage());
			writer.println("Resource doesn't exist or credentials are wrong");
		}

		deleteTemps(temp);
		

		date = new java.util.Date();
		long end = date.getTime();
		
		
		int duration = (int)((end - begin) / 1000);
		path += "?menu=indexReport&duration="+duration;
		path += "&name="+ indexName;
		path += "&docCount="+ docCount;
		path += "&index="+ newIndex;
		path += "&msg=OK";
		
		response.sendRedirect(path);
		writer.close();
	}
	
		
	
	
	private void sendError(String msg, String path, HttpServletResponse response){
		logger.error(msg);
		path += "?menu=indexReport&duration=0";
		path += "&name= NOT CREATED";
		path += "&docCount=0";
		path += "&msg="+ msg;
		try{
			response.sendRedirect(path);
			
		}catch(Exception e){
			logger.error("can't redirect");
		}
	}
}
