package org.injac.indexing.rss;

import java.io.IOException;

import org.injac.indexing.util.PathManager;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.injac.indexing.beans.ReportBean;
import org.injac.indexing.util.BeanPhoenix;

public class IndexRSS extends GenericRSSServlet {
	static Logger logger = Logger.getLogger("INJAC_INDEX");
	private ResourceBundle resBundle;
	private String upnode;
	private String baseURL;
	private boolean adaptURL = false;
	static final String DESC = "List of lastly indexed documents for index ";
	static final String TITLE = "Lastly indexed documents";
	static final int DEFAULT_LENGTH=10;
	public void service(ServletRequest request, ServletResponse res)
			throws ServletException, IOException {
		resBundle = ResourceBundle.getBundle("indexation");
		int length;
		String indexName = request.getParameter("name");
		if(indexName ==null)
			indexName="global";
		String lengthStr =request.getParameter("length");
		if(lengthStr != null){
			try {
				length = Integer.parseInt(lengthStr);
			}catch(NumberFormatException nfe){
				logger.error("bad length format : " +lengthStr);
				length = DEFAULT_LENGTH;
			}
		}else {
			length = DEFAULT_LENGTH;
		}
		upnode = request.getParameter("upnode");
		baseURL = request.getParameter("baseURL");
		adaptURL = (upnode!=null)&&(baseURL!=null);
		writer = res.getWriter();
		startRSS();
		String link = request.getServerName();
		startChannel(TITLE, link, DESC + indexName);
		fetchLastDocs(indexName, length);
		endChannel();
		endRSS();
		
	}

	private boolean fetchLastDocs(String indexName, int length){
		String indexPath = resBundle.getString("indexPath");
		String beanReportPath = ReportBean.getPath(indexPath, indexName);
		ReportBean lastReport = (ReportBean)BeanPhoenix.loadBean(beanReportPath);
		
		if(lastReport==null){
			logger.error("unable to load report bean : "+beanReportPath);
			return false;
		}else {
			int last = lastReport.getSize()-1;
			int count =0;
			while(count<length && last >=0){
				ReportBean.ReportLine line = lastReport.getLine(last--);
				if(line.isRoot()){
					startItem(line.getTitle(), processURL(line.getUrl()), line.getDescription());
					endItem();
					count++;
				}
			}
			return true;
		}
	}
	/**
	 * Translates webdavURL into injac Rendering URL
	 * @param webdavURL
	 * @return rendering url
	 */
	private String processURL(String webdavURL){
		if(adaptURL){
			String renderURL =PathManager.encodeURL(PathManager.renderURL(webdavURL, upnode, baseURL)); 
			renderURL = renderURL.substring(0, renderURL.lastIndexOf('/'));
			return renderURL; 
		}
		return webdavURL;
	}
}
