package httpserver;

import java.util.HashMap;
import java.util.Iterator;
import java.io.IOException;
import java.io.BufferedReader;

public class HttpRequest {
    private String method;
    private String protocol;
    private String path;
    private BufferedReader content;
    private HashMap<String,String> headers =
        new HashMap<String,String>();

    public HttpRequest( BufferedReader rd ) throws IOException {
        content = rd;
        String line = rd.readLine();
        if ( line == null ) {
            throw new RuntimeException("empty request");
        }
        String[] words = line.split("\\s+", 3);
        if ( words.length != 3 ) {
            throw new RuntimeException("bad request");
        }
        method = words[0];
        path = words[1];
        protocol = words[2];

        while( (line=rd.readLine()) != null ) {
            if ( line.length() == 0 ) break; 
            String[] s = line.split(":", 2);
            headers.put( s[0], s[1] );
        }
    }

    public String getMethod() {
        return method;
    }

    public String getPath() {
        return path;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader( String key ) {
        return headers.get( key );
    }

    public Iterator<String> getHeaderNames() {
        return headers.keySet().iterator();
    }
}
