import java.io.*;
import java.net.*;
import java.util.*;


/**
 * An encapsulation of an HTTP request
 *
 * This version:
 *
 *     Does not handle headers
 *     Does not handle query string parameters
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 0.0
 */
public class HttpRequest
{
    private String         method, requestURI, version;
    private URI            uri;

    /**
     * Default Constructor
     */
    public HttpRequest()
    {
       method          = null;       
       requestURI      = null;       
       version         = null;
       uri             = null;       
    }

    /**
     * Returns the name of the HTTP method with which this request was made, 
     * (for example, GET, POST, or PUT)
     *
     * @return  The method
     */
    public String getMethod()
    {
       return method;
    }

    /**
     * Returns the part of this request's URI from the protocol name 
     * up to the query string in the first line of the HTTP request
     *
     * @return   The URI
     */
    public String getRequestURI()
    {
	return uri.getPath();
    }

    /**
     * Returns the the URI including the protocol name, host, and path
     * but not the query string
     *
     * @return   The URL
     */
    public String getRequestURL()
    {
	return uri.getScheme()+"://"+getRequestURI();
    }

    /**
     * Read this request
     *
     * @param in  The HttpInputStream to read from
     */
    public void read(HttpInputStream in)
    {
       String             line, request, token, value;
       String[]           tokens;

       try
       {
          line = in.readHttpLine();

          tokens = line.split("\\s");

          method  = tokens[0];
          request = tokens[1];
          if (tokens.length > 2) version = tokens[2];
          else                   version = "HTTP/0.9";

          // Parse the URI
          tokens = request.split("?");
          requestURI   = tokens[0].substring(1);
          
          try
          {
             uri = new URI(requestURI);
          }
          catch (URISyntaxException urise)
          {
             uri = null;
          }

       } 
       catch (IndexOutOfBoundsException ioobe)
       {
          // There was a problem processing the request
       } 
       catch (IOException ioe)
       {
          // There was a problem reading the request or
          // processing the headers
       }
    }

    /**
     * Returns a String representation of this Object
     *
     * @return   The String representation
     */
    public String toString()
    {
       Enumeration   e;
       String        name, s, value;

       s  = "Method: \n\t" + getMethod() + "\n";
       s += "URI: \n\t"    + getRequestURI()+"\n";

       return s;
    }
}
