/*
 * @(#)HTTPRequest.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 30.04.2002
 */

#include "BufferedReader.h"
#include "Error.h"
#include "HTTPRequest.h"
#include "Log.h"
#include "StreamTokenizer.h"

HTTPRequest::HTTPRequest(BufferedReader &reader) {
	StreamTokenizer tokenizer(reader);

	if (tokenizer.nextToken() != tokenizer.TT_WORD)
		throw new Exception("method expected");
	method = tokenizer.sval;

	if (!method.equalsIgnoreCase("GET")
		&& !method.equalsIgnoreCase("HEAD"))
		return;

	if (tokenizer.nextToken() != tokenizer.TT_WORD)
		throw new Exception("URI expected");
	uri = tokenizer.sval;

	if (tokenizer.nextToken() != tokenizer.TT_WORD)
		throw new Exception("protocol expected");
	protocol = tokenizer.sval;

	if (tokenizer.nextToken() != tokenizer.TT_EOL)
		throw new Exception("EOL expected");

	// parse fields
	while (1) {
		if (tokenizer.nextToken() == tokenizer.TT_EOL)
			break;
		String fieldName = tokenizer.sval;

		if (tokenizer.nextToken() != tokenizer.TT_WORD
			|| !tokenizer.sval.equals(":"))
			throw new Exception(": expected");

		String field = "";
		if (tokenizer.nextToken() != tokenizer.TT_EOL) {
			field = field + tokenizer.sval;

			if (fieldName.equalsIgnoreCase("Host"))
				host = new String(field);

			int acceptLanguage = fieldName.equalsIgnoreCase(
				"Accept-Language");
			if (acceptLanguage)
				languages.add(tokenizer.sval);

			int i = 0;
			while (tokenizer.nextToken() != tokenizer.TT_EOL)
				if (i++ < 1000) {
					field = field + " " + tokenizer.sval;
					if (acceptLanguage && !tokenizer.sval.equals(","))
						languages.add(tokenizer.sval);
				}
		}

		log.debug("HTTPRequest", "- <%s> <%s>",
			fieldName.getBytes(), field.getBytes());
	}
}

HTTPRequest::HTTPRequest(HTTPRequest *request) {
	method = request->method;
	uri = request->uri;
	protocol = request->protocol;
	host = request->host;
	languages = request->languages;
	delete request;
}

HTTPRequest::~HTTPRequest() {
}
