package de.vc.jfox.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

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

import de.vc.jfo.Document;
import de.vc.jfo.renderer.OutputFormat;
import de.vc.jfo.rtf.RTFImporter;
import de.vc.jfo.rtf.listeners.SimpleDataSource;

/**
 * Simple servlet that fills an RTF template with GET or POST parameters and renders it finally to PDF. You need to setup the RTF template directory in your web.xml. Add an init paramter
 * "rtf-template-dir" and set it to a directory of your choice containing the RTF templates. Please look at /etc/web.xml in the extension directoy of JFO for an example.
 * 
 * @author not attributable
 * @version 1.0
 */
public class SimpleReportServlet extends HttpServlet {

  // ---- Members
  // ---------------------------------------------------------------

  /**
   * Directory of RTF templates on server.
   */
  private String rtfTemplateDir;

  private String password;

  // ---- Constructors ------------------------------------------------------

  // ---- public ------------------------------------------------------------

  public void init(ServletConfig c) throws ServletException {
    super.init(c);
    rtfTemplateDir = c.getInitParameter("rtf-template-dir");
    password = c.getInitParameter("password");
  }


  // ---- protected ---------------------------------------------------------

  protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    this.createReport(req, response);
  }


  protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    this.createReport(req, response);
  }


  protected void createReport(HttpServletRequest req, HttpServletResponse response) throws ServletException,
      IOException {

    if (password!=null && password.length()>0){
      String givenPw = (String) req.getAttribute("jfo:password");
      if (givenPw==null || !givenPw.equals(password)){
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid password send.");
        return;
      }
    }
    
    // determine RTF template path from requested PDF path
    String pdf = req.getServletPath();
    if (!pdf.toLowerCase().endsWith(".pdf")) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, "Supporting PDF only.");
      return;
    }

    String rtf = (String) req.getParameter("rtfFile");
    File rtfFile;
    if (rtf == null) {
      rtf = pdf.substring(0, pdf.length() - 3) + "rtf";
      rtfFile = new File(rtfTemplateDir, rtf);
    } else {
      rtfFile = new File(rtf);
    }

    if (!rtfFile.exists()) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, "RTF template " + rtfFile + " not found");
      return;
    }

    SimpleDataSource ds = new SimpleDataSource();
    Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
      String name = e.nextElement().toString();
      String[] values = req.getParameterValues(name);

      if (name.endsWith("[]"))
        ds.setTableColumn(name.substring(0, name.length() - 2), values);
      else if (values == null)
        ds.setEmptyValue(name);
      else if (values.length == 1)
        ds.setValue(name, values);
      else {
        ds.setTableColumn(name, values);
      }
    }

    RTFImporter i = new RTFImporter();
    i.addFieldListener(ds);
    Document doc = i.importDocument(rtfFile.getAbsolutePath());

    response.setContentType("application/pdf");
    doc.render(OutputFormat.PDF, response.getOutputStream());
  }

  // ---- package -----------------------------------------------------------

  // ---- private -----------------------------------------------------------

}
