package org.injac.indexing.show;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;

public class ViewDocumentFields extends IndexReaderServlet {

	protected void show(HttpServletRequest request, String indexName,
			File indexDir, PrintWriter writer) {
		int i = checkParseInt(request.getParameter("doc"), 0);
		try {
			IndexReader reader = IndexReader.open(indexDir);
			if (!reader.isDeleted(i)) {
				Document d = reader.document(i);
				// construct popup
				String htmlFields = "<ul class=\"indexfields\">";
				java.util.Enumeration fields = d.fields();
				while (fields.hasMoreElements()) {
					Field field = (Field) fields.nextElement();
					if ("url body description".indexOf(field.name()) == -1) {
						if (field.stringValue().length() < MAX_MD_DISPLAY_SIZE)
							htmlFields += "<li>" + field.name() + " : "
									+ field.stringValue() + "</li>";
						else {
							String shortValue = field.name()
									+ " : "
									+ field.stringValue().substring(0,
											MAX_MD_DISPLAY_SIZE) + "...";
							htmlFields += "<li>" + shortValue + "</li>";
						}
					}

				}
				htmlFields += "</ul><br/><br/><br/>";
				
				String widgetID="htmlfields";
				
				writer.println("<div id=\""+widgetID+"\">");
				String titleBar = getWidgetTitleBar();
				titleBar = titleBar.replaceAll("\\$title","champs indexés");
				titleBar = titleBar.replaceAll("\\$widgetId","'"+widgetID+"'");
				writer.println(titleBar);
				String content = getWidgetContent();
				content = content.replaceAll("\\$content", htmlFields);
				writer.println(content);
				writer.println("</div>");
				reader.close();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}
	
	
}
