/**
 * Copyright 2007 Ben Bucksch
 * BSD license
 */

package org.bucksch.httpserver;
import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.util.*;
import org.bucksch.zeipis.all.Util;

public class HTTPRequest
{
  HTTPRequest(String method, URL url, Map<String, String> headers, InetAddress client, InputStream in, OutputStream out)
  {
    myMethod = method;
    myURL = url;
    myRequestHeaders = headers;
    myResponseHeaders = new HashMap<String, String>();
    myClient = client;
    myIn = in;
    myOut = out;
  }
  public String method() { return myMethod; }
  public URL getURL() { return myURL; }
  /**
   * What the handler registered as URL prefix.
   * The part of the URL between hostname and URLRest,
   * not including starting "/", but including trailing "/" (if any).
   */
  public String getURLPrefix() { return myURLPrefix; }
  /**
   * The part of the URL path (dir and filename, no query) after the URL prefix.
   */
  public String getURLRest() { return myPathRest; }
  public Map<String, String> getRequestHeaders() { return myRequestHeaders; }
  public Map<String, String> getResponseHeaders() { return myResponseHeaders; }
  public InetAddress client() { return myClient; }
  public InputStream getRequestBody() { return myIn; }
  public OutputStream getResponseBody() { return myOut; }
  /**
   * Starts sending a response to the client.
   * Must be called before sending anything to the OutputStream of getResponseBody.
   * 
   * @param responseCode A HTTP code, @see RFC 2616, Section 10
   *     <http://www.apps.ietf.org/rfc/rfc2616.html>
   */
  public void sendResponseHeaders(int responseCode, boolean close)
    throws IOException
  {
    BufferedWriter response = new BufferedWriter(new OutputStreamWriter(myOut));
    response.write("HTTP/1.0 " + responseCode + " OK" + HTTPServer.newline);
    for (String headerName : myResponseHeaders.keySet())
      response.write(headerName + ": " + myResponseHeaders.get(headerName) + HTTPServer.newline);
    response.write(HTTPServer.newline);
    response.flush();
    if (close)
      response.close();

    Util.debug("HTTP/1.0 " + responseCode + " OK");
    for (String headerName : myResponseHeaders.keySet())
      Util.debug(headerName + ": " + myResponseHeaders.get(headerName));
    if (close)
      Util.debug("Closing connection");
  }
  public void close()
    throws IOException
  {
    myOut.close();
  }

  // Internal
  void setPathPrefix(String urlPrefix) { myURLPrefix = urlPrefix; }
  void setPathRest(String urlRest) { myPathRest = urlRest; }
  // Data
  protected String myMethod;
  protected URL myURL;
  protected String myURLPrefix;
  protected String myPathRest;
  protected Map<String, String> myRequestHeaders;
  protected Map<String, String> myResponseHeaders;
  protected InetAddress myClient;
  protected InputStream myIn;
  protected OutputStream myOut;
}
