/*
 * @(#)HTTPRequest.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2002-2003 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) {
	contentLength = 0;

	StreamTokenizer tokenizer(reader);

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

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

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

	int res;
	while (true) {
		// deal with ":" in URIs
		res = tokenizer.nextToken();
		if (res != tokenizer.TT_WORD
				|| !tokenizer.sval.equals(":"))
			break;
		uri = uri + ":";
		res = tokenizer.nextToken();
		if (res != tokenizer.TT_WORD)
			break;
		uri = uri + tokenizer.sval;
	}

	if (res != 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);
				}

			if (fieldName.equalsIgnoreCase("Content-Length"))
				contentLength = Integer::getInt(field.getBytes());
		}

		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;
	contentLength = request->contentLength;
	delete request;
}

HTTPRequest::~HTTPRequest() {
}
