package com.tivoli.jmx.tutorial.server;

import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.util.Date;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.Socket;

public class Request implements Comparable {
  private java.net.Socket socket;
  private long timeStamp;
  private java.lang.String method;
  private java.lang.String uri;
  private java.lang.String protocol;

  public Request(long timeStamp, Socket socket) {
    this.timeStamp = timeStamp;
    this.socket = socket;
  }

  public void close() {
    try {
      if (socket != null)
        socket.close();
    } catch (IOException x) {
      System.err.println(x);
    }
  }

  public int compareTo(Object request) {
    if (!(request instanceof Request)) {
      throw new ClassCastException("Not a Request");
    }

    return (int) (this.timeStamp - ((Request) request).getTimeStamp());
  }

  public String getMethod() {
    return method;
  }

  public java.io.OutputStream getOutputStream() throws IOException {
    return socket.getOutputStream();
  }

  public String getProtocol() {
    return protocol;
  }

  public long getTimeStamp() {
    return this.timeStamp;
  }

  public String getURI() {
    return uri;
  }

  public void log() {
    Date date = new Date(timeStamp);
    synchronized (Httpd.logfile) {
      try {
        OutputStream out = new BufferedOutputStream(Httpd.logfile.getOutputStream());
        out.write(date.toString().getBytes());
        out.write((byte) '\t');
        out.write(method.toString().getBytes());
        out.write((byte) '\t');
        out.write(uri.toString().getBytes());
        out.write((byte) '\r');
        out.write((byte) '\n');
        out.flush();
      } catch (IOException x) {
        System.err.println("Can't log request: " + x);
      }
    }
  }

  public void open() throws java.net.ProtocolException {
    try {
      InputStream in = new BufferedInputStream(socket.getInputStream());
      StringBuffer requestBuffer = new StringBuffer();
      for (int c = in.read(); c != '\r' && c != '\n' && c != -1; c = in.read()) {
        requestBuffer.append((char) c);
      }
      String request = requestBuffer.toString();
      request.trim();
      StringTokenizer requestTokenizer = new StringTokenizer(request);
      method = requestTokenizer.nextToken();
      uri = requestTokenizer.nextToken();
      protocol = requestTokenizer.nextToken();
    } catch (Exception x) {
      throw new java.net.ProtocolException(x.getMessage());
    }
  }
}