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

public class ConnectionHandler extends Thread{

    Socket in;
    BufferedReader socket_in;
    PrintStream socket_out;
    config conf;

    ConnectionHandler(Socket in, config conf) {
	this.in = in;
	this.conf = conf;
	try {
	    socket_in = new BufferedReader(new InputStreamReader(this.in.getInputStream()));
	    socket_out = new PrintStream(this.in.getOutputStream());
	} catch (Exception e) {
	    System.err.println("ConnectionHandler: failed to get InputStream from socket!");
	}

	start();
    }
    
    public void run() {
	
	String request = new String();
	boolean done = false;
	boolean previous = false;
	
	while (!done) {
	    try {
		if (socket_in.ready()) {
		    request = socket_in.readLine();
		    done = handle_request(request);
		    previous = true;
		} else {
		    previous = false;
		}
		
		if (!previous)
		    sleep(1);

	    } catch (Exception e) {}
	}

	System.err.println("Closing socket");

	try {
	    socket_in.close();
	    socket_out.close();
	    in.close();
	    this.in.close();
	} catch (Exception e) {
	    System.err.println("Could not close socket!");
	}
	
    }

    boolean handle_request(String request) {
	String req;
	boolean ans = false;
	int i=0, j=0;

	System.err.println("Handling request:" + request);
	if (request.length()>0) {
	    while(request.charAt(i++)!='\0'&&request.charAt(i)!=' ');
	    j=i;
	    while(request.charAt(j++)!='\0'&&request.charAt(j)!=' ');
	}

	req = request.substring(0,i);
	
	if (req.equals("GET")) {
	    //get_file(request.substring(i+1,j), request);
	    //ans = true;
	} else if (req.equals("Host:")) {
	    
	} else if (req.equals("User-Agent:")) {

	} else {

	}
	
	return ans;
    }
    
    void get_file(String file) {
	FileReader fin;
	boolean die = false;
	String return_string = "what the!";
	
	if (file.startsWith("/")) {
	    file = file.substring(1, file.length());
	    file = conf.docroot + file;
	}
	System.err.println("get file: '" + file + "'");
	
	try {
	    fin = new FileReader(file);
	} catch (Exception e) {
	    return_string = error.file_not_found404();
	    die = true;
	}

	if (!die) {
	    

	}
	
	System.err.println("Return string = '" + return_string + "'.");
	socket_out.println(return_string);
    }

    String readcrlf(BufferedReader s) {
	String str = new String();
	char c = '\0', last = '\0';
	boolean done = false;

	try {
	    c = (char)s.read();	
	} catch (Exception e) {}

	while (!done) {
	    str = str + c;
	    if (c=='\10'&&last=='\13') {
		done = true;
	    } else {
		last = c;
		try {
		    c = (char)s.read();
		} catch (Exception e) {}
	    }
	}
	str = str.substring(0,str.length()-1);
	return str;
    }
}


