package org.injac.indexing.show;

import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.injac.indexing.beans.IndexListBean;
import org.injac.indexing.util.BeanPhoenix;
import org.injac.indexing.util.WidgetManager;
import java.io.PrintWriter;
abstract public class IndexReaderServlet extends HttpServlet {
	static Logger logger = Logger.getLogger(IndexReaderServlet.class);
	protected ResourceBundle resBundle;

	protected final int MAX_MD_DISPLAY_SIZE = 25;

	protected String indexPath;

	protected int index = -1;

	public IndexReaderServlet() {
		super();
		resBundle = ResourceBundle.getBundle("indexation");
	}
	
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		javax.servlet.ServletContext context = getServletContext();
		IndexListBean indexListBean = (IndexListBean) context
				.getAttribute("indexListBean");

		if (indexListBean == null) {
			indexListBean = (IndexListBean) BeanPhoenix.loadBean(IndexListBean.class);
			if (indexListBean != null) {
				context.setAttribute("indexListBean", indexListBean);
			}
		}

		indexPath = resBundle.getString("indexPath");
		String indexS = request.getParameter("index");
		index = checkParseInt(indexS, 0);
		response.setContentType("text/html; charset=iso-8859-1");
		PrintWriter writer = response.getWriter();

		String indexName = indexListBean.getName(index);
		File indexFile = new File(indexPath + "/" + indexName);
		if (!indexFile.exists()) {
			writer.println("<p>Error: index not created yet ! "
					+ "Please create index first and try again.'/p>");
		} else {
			
			show(request, indexName, indexFile, writer);
			
		}

		//writer.close();
	}

	abstract protected void show(HttpServletRequest request, String indexName, File indexDir, PrintWriter writer);

	protected int checkParseInt(String valueStr, int defaultValue) {
		int result = defaultValue;
		if (valueStr != null) {
			try {
				result = Integer.parseInt(valueStr);
			} catch (Exception e) {
				// NOP
				result = defaultValue;
			}
		}
		return result;
	}
	
	protected String getWidgetTitleBar(){
		return WidgetManager.getTitleBar(resBundle);
	}
	protected String getWidgetContent(){
		return WidgetManager.getContent(resBundle);
	}
}
