import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class USeek extends HttpServlet {
  protected final String CONFIGFILENAME = "useek.cfg";

  protected static String templatePath, urlRoot, searchUrl;
  protected static String url;

  protected static boolean local;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
//    log("did super.init()");

    if(templatePath == null)
      templatePath = new String("/opt/app/suitespot/plugins/java/servlets/templates/");
    searchUrl = new String("http://search.mit.edu:8765/saquery.spy");
    String t;
    if((t = getInitParameter("local")) == null)
      local = false;
    else if(!t.equals("true"))
      local = false;
    else
      local = true;
    //    log("finished init");
  }

  public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    // CSP what if no path info?

    Date d = new Date();
    System.err.println("USeek: service request start: " + d);

    ServletOutputStream os;
    PrintWriter pw = new PrintWriter(res.getOutputStream());
    StringBuffer page = null;
    String path = req.getPathInfo();
    String fullPath = null;
    if(urlRoot == null)
      urlRoot = new String(req.getServerName());

    res.setContentType("text/html");
    //    log("doing tests");

    boolean errorPage = false;
    if(path != null) {
      if(path.charAt(0) == '/')
	path = path.substring(1, path.length());
      if(path.equals("/errorpage"))
	errorPage = true;
      else {
	fullPath = new String(templatePath + path);

	String mt = getServletContext().getMimeType(fullPath);
	//	log("file: " + fullPath + ", mime type: " + mt);

	boolean bail = false;
	if(!(fullPath.endsWith(".html") || fullPath.endsWith(".htm")))
	  bail = true;

	if(bail) {
	  res.sendError(406);
	  return;
	}
      }
    }

    //    log("preparing output");

    try {
      if(path == null) {
	CheckResponse cr = new CheckResponse(req, res);
	cr.getResponse();
      } else if(errorPage) {
	page = ErrorPage.doPage(req);
      } else {
	page = new StringBuffer();
	File f = new File(fullPath);
	FileInputStream fin = null;
	fin = new FileInputStream(f);
	DataInputStream in = new DataInputStream(fin);

	String s = null, t;
	boolean done = false;
	TokenReplacer tr = null;
	try {
	  s = in.readLine();
	}
	catch (IOException e) {
	  throw new TemplateReadException(fullPath);
	}
	if(s != null)
	  if((t = TokenReplacer.getNextToken(s)) != null)
	    if(t.startsWith("templateType:")) {
	      String temptype = TokenReplacer.chopToken(t);
	      //	      System.out.println("temptype: " + temptype);
	      if(temptype != null)
		if(temptype.equals("useek"))
		  tr = new SearchPage(req, templatePath, searchUrl);
		  // tr = new CnumRep(req, urlRoot, this);
	    }
	if(tr == null)
	  page.append(s + "\n");
      
	while(true) {
	  try {
	    s = in.readLine();
	  }
	  catch (IOException e2) {
	    throw new TemplateReadException(fullPath);
	  }
	  if(s == null)
	    break;
	  if(tr != null)
	    while((t = TokenReplacer.getNextToken(s)) != null)
	      s = tr.replaceToken(s, t);
	  page.append(s + "\n");
	}
      } // if path == null
    } // try
    catch (URLFileException uf) {
      URL u = new URL(uf.getMessage());
      String msg = new String("could not open file " + u.getFile() + " on host " + u.getHost());
      page = ErrorPage.doPage(msg);
      log(msg);
    }
    catch (TemplateReadException tr) {
      // template file read error
      String msg = new String("error reading from template file " + tr.getMessage());
      page = ErrorPage.doPage(msg);
      log(msg);
    }
    catch (IOException io) {
      String msg = new String();
      if(io instanceof UnknownHostException) {
	msg = "unknown host: " + io.getMessage();
	page = ErrorPage.doPage(msg);
	log(msg);
      } else if(io instanceof MalformedURLException) {
	msg = io.getMessage();
	page = ErrorPage.doPage(msg);
	log(msg);
      } else if(io instanceof FileNotFoundException) {
	msg = "could not open template file " + io.getMessage();
	page = ErrorPage.doPage(msg);
	log(msg);
      } else {
	String cn = io.getClass().getName();
	int i = cn.lastIndexOf('.');
	if(i == -1)
	  i = 0;
	msg = cn.substring(i+1, cn.length()) + ": " + io.getMessage();
	page = ErrorPage.doPage(msg);
	log(msg);
      }
    }
    catch (InternalException g) {
      String msg = new String("Internal error: " + g.getMessage());
      page = ErrorPage.doPage(msg);
      log(msg);
    }
    catch (APIException g) {
      String msg = new String("API error: " + g.getMessage());
      page = ErrorPage.doPage(msg);
      log(msg);
    }
    finally {
      /* flush and close the PrintWriter */
      if(page != null) {
	pw.print(page);
	pw.flush();
      }
      pw.close();
    }

    d = new Date();
    System.err.println("USeek: service request end: " + d);
  } // end of service()
} // end of class ReqInfoServlet
