/*
 * 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;
/**
 * 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)
			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 int saveBean(HttpServletResponse response,HttpSession session,String indexName,String url,String user,String password,int mdMode){
		
		javax.servlet.ServletContext context =session.getServletContext();
		IndexListBean indexListBean = (IndexListBean)context.getAttribute("indexListBean");
		int newIndex = -1;
		if(indexListBean!=null){
			newIndex = indexListBean.addIndex(indexName,url,user,password,mdMode);
			if(newIndex==-1)
			{
				sendError("Index name already exists :"+indexName, path, response);
				return -1;
			}
			context.setAttribute("indexListBean", indexListBean);
			//	 save bean
			String beanPath = indexPath+"/";
			
			BeanPhoenix.saveBean(indexListBean, beanPath+indexListBean.getClass().getName()+".ser");
		}else {
			sendError("can't access indexListBean : redirecting to main page", path, response);
		}
		return newIndex;
		
	}
	private void undoSaveBean(Object bean, int newIndex){
		String beanPath = indexPath+"/";
		
		BeanPhoenix.saveBean(bean, beanPath+bean.getClass().getName()+".ser");
	}
	
	
	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");
		}
	}
}
