/*
 * 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.ResourceBundle;
import java.util.Date;
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 UpdateIndexingServlet extends GenericIndexingServlet {
	private static String FAILED = "FAILED";
	/**
	 * 
	 */
	private static final long serialVersionUID = 944029745798300027L;
	private ResourceBundle resBundle;
	
	public UpdateIndexingServlet() {
		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");
		String msg = "OK";
		int mdMode= extractMode(mode);
		int docCount=0;	
		
		indexPath= resBundle.getString("indexPath");
		String path = request.getRequestURL().toString();
		path = path.substring(0,path.lastIndexOf('/'));
		int updatedIndex = -1;
		// update application bean indexListBean 
		HttpSession session = request.getSession();
		WebdavConnection webdavConnection = new WebdavConnection(session);
		try{
			webdavConnection.connect(url, user, password);
		}catch(Exception e){
			sendError(FAILED + " unable to connect to "+url, path, response);	
			return;
		}
		
		javax.servlet.ServletContext context =session.getServletContext();
		IndexListBean indexListBean = (IndexListBean)context.getAttribute("indexListBean");
		if(indexListBean!=null){
			updatedIndex = indexListBean.getIndexForName(indexName);
			
		}else {
			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();
		File temp = createFiles(indexName, false);
		
		
		try {
			HttpURL hrl = new HttpURL(url);
			hrl.setUserinfo(user, password);
			WebdavFile wf = new WebdavFile(hrl);
			String contextPath = getServletContext().getRealPath("/");
			logger.debug("REALPATH : "+contextPath);
			UpdateBrowser updateBrowser = new UpdateBrowser(contextPath, webdavConnection);
			docCount = updateBrowser.indexAll(wf,indexName,mdMode);

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

		catch (HttpException he) {
			msg = FAILED+" HttpException : "+he.getLocalizedMessage();
			logger.error(msg);
			writer.println("HttpException<br>");
		} catch (IOException ioe) {
			msg =FAILED+" IOException: " + ioe.getLocalizedMessage();
			logger.error(msg);
			writer.println("IOException<br>");
		} catch (ConnectionException ce) {
			msg =FAILED + " ConnectionException :"+ce.getLocalizedMessage();
			logger.error(msg);
			writer.println("Resource doesn't exist or credentials are wrong");
		} catch (NullPointerException npe) {
			msg =FAILED + " NullPointerException : "+npe.getLocalizedMessage();
			logger.error(msg);
			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="+ updatedIndex;
		path += "&msg="+msg;
		if(updatedIndex!=-1){
			// update modification date
			indexListBean.setModificationDate(updatedIndex, date.getTime());
			saveBean(indexListBean);
		}
		response.sendRedirect(path);
		writer.close();
	}
	private void saveBean(Object bean){
		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 UPDATED";
		path += "&docCount=0";
		path += "&msg="+ msg;
		try{
			response.sendRedirect(path);
			
		}catch(Exception e){
			logger.error("can't redirect");
		}
	}
}
