package com.yaz.webserver;

import java.net.*;
import java.io.*;

public class SimpleRequestHandler extends Thread {

  private int port = 80;
  private ServerSocket socket;
  private Socket client = null;
  boolean shouldRun = false;

  public SimpleRequestHandler() {
    try {
      System.out.println("Server initializing...");
      init();
    } catch (IOException e) {
      System.out.println("Could not bind to the port "+ port);
      return;
    }
  }

  private void init() throws IOException {
    shouldRun = true;
    socket = new ServerSocket(port);
  }


  public void run() {
    while (shouldRun) {
      // do something useful
      try {
        client = socket.accept();
        BufferedReader in =
          new BufferedReader(new InputStreamReader(client.getInputStream()));
        BufferedWriter out =
          new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        // for now, disregard whatever a client sent you
        StringBuffer request = new StringBuffer();
        String aLine = null;
        while ((aLine = in.readLine()) != null) {
          System.out.println(aLine);
          if (aLine.length() == 0 || aLine.trim().equals("")) {
          break;
          }
        }
        /* use CLRF or PrintWriter.println() to add return/line feed
         * characters at the end of each line.
         * YOU MUST ADD EXTRA BLANK LINE AFTER THE HEADER SECTION
         */
        System.out.println("Done reading request");
        // for now return a static content
        //out.println("HTTP/1.1 200 OK\r\n");
        out.write("HTTP/1.1 200 OK\r\n");
        out.write("Date: Fri, 31 Dec 1999 23:23:29 GMT\r\n");
        //out.println("Last-Modified: Fri, 31 Dec 1999 23:23:25 GMT");
        out.write("Content-Type: text/html\r\n");
        String content = new String("<html><h1>You got it!!!</h1></html>");
        System.out.println("Content-Length: " + content.length());
        out.write("Content-Length: "+ content.length()+4 + "\r\n");
        out.write("\r\n");
        out.write(content);
        System.out.println("Done writing it out to OutputStream");
        out.flush();

        in.close();
        out.close();
        client.close();
      } catch (IOException e) {
        System.out.println("Error:");
        e.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {

    SimpleRequestHandler handler = new SimpleRequestHandler();
    if (handler != null)
      handler.start();
  }
}