package httpserver;

import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;

public class HttpResponse {
    public static final int RESP_OK = 200;
    public static final int RESP_FILE_NOT_FOUND = 404;
    public static final int RESP_METHOD_NOT_ALLOWED = 405;

    private OutputStream out;
    private String contentType = "text/html";
    private byte[] headers = null;
    private int responseCode = RESP_OK;
    private boolean headerSent = false;

    public HttpResponse( OutputStream out ) {
	this.out = out;
    }

    public void setHeaders( byte[] headers ) {
	this.headers = headers;
    }

    public void setContentType( String t ) {
        contentType = t;
    }

    public void setStatus( int code ) {
        responseCode = code;
    }

    public OutputStream getOutputStream() {
	if ( !headerSent ) {
	    headerSent = true;
	    sendResponseStart();
	}
        return out;
    }

    public PrintWriter getWriter() {
	if ( !headerSent ) {
	    headerSent = true;
	    sendResponseStart();
	}
        return new PrintWriter(
	    new BufferedWriter( new OutputStreamWriter( out )));
    }

    private void sendResponseStart()  {
	try {
	    String s = "HTTP/1.0 " + responseCode + " see body\n";
	    out.write( s.getBytes() );
	    s = "Connection: close\n";
	    out.write( s.getBytes() );
	    s = "Content-Type: " + contentType + "\n";
	    out.write( s.getBytes() );
	    if ( headers != null ) {
		out.write( headers );
	    }
	    headers = null;
	    out.write( '\n' );
	    out.flush();
	}
	catch( IOException e ) {
	    throw new RuntimeException( e.getMessage() );
	}
    }

    public void sendError( int code, String message )  {
	PrintWriter pw = getWriter();
        pw.println("HTTP/1.0 " + code + " see body");
        pw.println("Connection: close");
        pw.println("Content-Type: text/html");
        pw.println();
        pw.println("<html><body><pre>");
	pw.println( message );
	pw.println("</pre></body></html>");
        pw.flush();
    }
}
