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

import org.injac.indexing.index.*;
import java.io.File;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.injac.indexing.index.GenericIndexingServlet;


import javax.servlet.ServletContext;
/**
 * Classe permettant de faire l'indexation d'une chaîne record OAI 
 * 
 * mode direct : le record est passé en paramètre
 * 		- record
 * Autres paramètres :
 * 		- name : nom de l'index utilisé
 * 
 * Utilise la session utilisateur pour stocker une instance de ExistIndexing
 * 
 * @author François Jannin, ENSEEIHT 2006
 */
public class StringOAIIndexingServlet extends GenericIndexingServlet {

	private ResourceBundle resBundle;

	public StringOAIIndexingServlet() {
		super();
		resBundle = ResourceBundle.getBundle("indexation");
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		
		String encoding =request.getCharacterEncoding();
		
		logger.debug("encoding : "+encoding);
		String record;
		String repositoryName;
		String os =System.getProperty("os.name");
		boolean isWindows =  (os.toUpperCase().indexOf("WINDOWS") !=-1);
		// system dependant actions
		if(isWindows){
			record = new String(request.getParameter("record").getBytes(), "utf-8");
			repositoryName = new String(request.getParameter("repositoryName").getBytes(),"utf-8");
		}else {
			if(encoding==null){
					encoding= resBundle.getString("oai.encoding");
					request.setCharacterEncoding(encoding);
			}
			
			record = request.getParameter("record");
			repositoryName = new String(request.getParameter("repositoryName").getBytes(),encoding);
		}		
		
		String indexName = request.getParameter("name");
		String update = request.getParameter("update");
		String openclose = request.getParameter("openclose");
		boolean open = (openclose != null ? openclose.equals("open") : false);
		boolean close = (openclose != null ? openclose.equals("close") : false);
		boolean updateMode = false;
		HttpSession session = request.getSession();
		if(update!=null){
			updateMode = (update.equalsIgnoreCase("true"));
		}
		indexPath = resBundle.getString("indexPath");
		String url = request.getRemoteHost();
		if(open){
			int newIndex = saveBean(response, session,indexName,url,"ori","ori",1);
			if(newIndex==-1){
				response.sendError(201,"can't access indexListBean");
				return;
			}	
			
		}
			
		response.setContentType("text/xml");
		java.io.PrintWriter writer = null;
		// create or get existing directory
		File index = createIndexDirectory(indexName, false);	
		if (!index.exists()) {
			response.sendError(201, "Error: index " + indexName
					+ " not created yet ! "
					+ "Please create index first and try again.'");
		} else {
			if(logger.isDebugEnabled()){
				writer = response.getWriter();
				writer.println("<indexationResult>");
				
				
			}
			try {
				ServletContext context = getServletContext();
				String client = request.getRemoteAddr();
				String indexinClass = resBundle.getString("oai.indexing.class");
				
				IIndexing oaiIndexing = (IIndexing)context.getAttribute(client+"StringOAIIndexing"+indexName);
				if(oaiIndexing == null){
						try{
						oaiIndexing = (StringOAIIndexing)Class.forName(indexinClass).newInstance();
						oaiIndexing.postCreate(indexName);
					}catch(Exception e){
						oaiIndexing = new StringOAIIndexing(indexName);
					}
					context.setAttribute(client+"StringOAIIndexing"+indexName,oaiIndexing );
				}
				if(open){
					oaiIndexing.open(updateMode);
				}
				boolean 	result = (url =oaiIndexing.index(record, repositoryName,updateMode)) != null;
				if (logger.isDebugEnabled()) {
					String msg = "Document (encoding="+encoding+": " + url + (result ?
					 " added to index or yet indexed."
					:" not added to index for some reason (see logs)");
					logger.debug(msg);
					writer.println("<p>"+msg+"</p>");	
				}
				if(close){
					oaiIndexing.close();
				}
				
				
			} catch (Exception he) {
				logger.error(he + " : "+ he.getLocalizedMessage());
				if(logger.isDebugEnabled()){
					writer.println("<p>"+he + " : "+ he.getLocalizedMessage()+"</p>");
				}
				else{
					response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
					response.flushBuffer();
				}
			}
		}
		if(logger.isDebugEnabled()){
			writer.println("</indexationResult>");
			writer.close();
		}else{
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();
		}
			
		
	}

	
	
}
