import baf.guide.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class items extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/html");
    ServletOutputStream out = res.getOutputStream();

    try {
      String path = req.getPathInfo();
      Item item = null;

      int second = path.indexOf('/', 1);
      if (second == -1) {
	// No second slash - send a redirect
	if (path.equals("/all")) Game.reviewsPage(out);
	else if (path.equals("/recent")) {
	  Index idx = Index.forTag(":c");
	  idx.update();
	  String partial = idx.itemAt(idx.size()-1).url;
	  String url = HttpUtils.getRequestURL(req).toString();
	  int delimitor = url.indexOf('/', url.indexOf("//")+2);
	  url = url.substring(0, delimitor)+partial;
	  res.sendRedirect(url);
	} else {
	  StringBuffer url = HttpUtils.getRequestURL(req);
	  url.append('/');
	  res.sendRedirect(url.toString());
	}
      } else if (second == path.length()-1) {
	// URL indicates an index
	if (path.equals("/games/")) Game.indexPage(out);
	else {
	  Index index = Index.forPath(path);
	  index.page(out);
	}
      } else {
	// URL indicates an item
	try {
	  Item.forPath(path).page(out);
	} catch (IllegalArgumentException e) {
	  res.sendError(res.SC_NOT_FOUND);
	  return;
	} catch (NoGamesException e) {
	  res.sendError(res.SC_NOT_FOUND);
	  return;
	}
      }
      doGC();
    } catch (Throwable t) {
      out.println("<p>There has been an error in Baf's Page Generator.<br>");
      out.println("Please send the following to <a href=mailto:carl@wurb.com>carl@wurb.com</a><br>");
      out.println("<pre>");
      t.printStackTrace(new PrintWriter(out, true));
      out.println("</pre>");
      doGC();
    }
  }

  int gcount = 0;

  /** On every 10th call, collect garbage.
   */
  void doGC() {
    gcount++;
    if (gcount >= 10) {
      System.gc();
    }
  }

  public String getServletInfo() {
    return "Create a page for the Item in Baf's Guide specified by the URL";
  }
}
