package be.jeffcheasey88.peeratcode.framework;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpWriter{

	private OutputStream out;
	private BufferedWriter writer;

	public HttpWriter(Socket socket) throws Exception{
		this.out = socket.getOutputStream();
		this.writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
	}
	
	public HttpWriter(HttpWriter origin) throws Exception{
		this.out = origin.out;
		this.writer = origin.writer;
	}

	public void write(byte[] buffer) throws IOException{
		this.out.write(buffer);
		this.out.flush();
	}

	public void write(String message) throws IOException{
		this.writer.write(message);
	}

	public void flush() throws IOException{
		this.writer.flush();
	}

	public void close() throws IOException{
		this.writer.close();
	}
	
	public void response(int code, String... headers) throws Exception{
		write("HTTP/1.1 "+code+codeMessage(code)+"\n");
		for(String header : headers) write(header+"\n");
		write("\n");
		flush();
		StackTraceElement[] e = Thread.currentThread().getStackTrace();
		System.out.println(e[2]+" -> response "+code);
	}
	
	private static String[] HEIGHTBITS = new String[7];
	private static String[] NINEBITS = new String[206];
	
	static {
		HEIGHTBITS[0] = " OK";
		HEIGHTBITS[1] = " Created";
		HEIGHTBITS[2] = " Accepted";
		HEIGHTBITS[3] = " Non-Authoritative Information";
		HEIGHTBITS[4] = " No Content";
		HEIGHTBITS[5] = " Reset Content";
		HEIGHTBITS[6] = " Partial Content";
		
		NINEBITS[0] = " Multiple Choices";
		NINEBITS[1] = " Moved Permanently";
		NINEBITS[2] = " Temporary Redirect";
		NINEBITS[3] = " See Other";
		NINEBITS[4] = " Not Modified";
		NINEBITS[5] = " Use Proxy";
		
		NINEBITS[100] = " Bad Request";
		NINEBITS[101] = " Unauthorized";
		NINEBITS[102] = " Payment Required";
		NINEBITS[103] = " Forbidden";
		NINEBITS[104] = " Not Found";
		NINEBITS[105] = " Method Not Allowed";
		NINEBITS[106] = " Not Acceptable";
		NINEBITS[107] = " Proxy Authentication Required";
		NINEBITS[108] = " Request Time-Out";
		NINEBITS[109] = " Conflict";
		NINEBITS[110] = " Gone";
		NINEBITS[111] = " Length Required";
		NINEBITS[112] = " Precondition Failed";
		NINEBITS[113] = " Request Entity Too Large";
		NINEBITS[114] = " Request-URI Too Large";
		NINEBITS[115] = " Unsupported Media Type";
		NINEBITS[123] = " Locked";
		NINEBITS[125] = " Too Early";
		
		NINEBITS[200] = " Internal Server Error";
		NINEBITS[201] = " Not Implemented";
		NINEBITS[202] = " Bad Gateway";
		NINEBITS[203] = " Service Unavailable";
		NINEBITS[204] = " Gateway Timeout";
		NINEBITS[205] = " HTTP Version Not Supported";
	}
	
	private static String codeMessage(int code){
		if(code == 100) return " Continue";
		if(code >> 8 == 0) return HEIGHTBITS[code-200];
		return NINEBITS[code-300];
	}
	
}