
#include "array.h"

#include "header.h"

class headerManager{

	struct array * headers	= new array();

	parse( char * headerContent ) {

		array * headerRows	= headerContent->split("\n");

		int headerCount		= headerRows->length();

		for (int i = 1; i < headerCount; ++i)
		{

			char * headerRow		= headerRows->get( i );

			array * headerRowParts	= headerRow->split(":");

			int headerRowPartsCount	= headerRowParts->length();


			if( headerRowPartsCount == 2 ) {

				char * headerName	= headerRowParts->get( 0 );

				char * headerValue	= headerRowParts->get( 1 );

				//printf("%-20s	%-30s \n", headerName, headerValue->removeWhitespace());

				//printf("header value:		%s\n\n", headerValue->removeWhitespace() );

				this->add( headerName, headerValue->removeWhitespace() );

			}

		}

		printf("\n\n");

	}

	void display() {

		struct array * headerRows	= this->headers;

		int headerCount		= headerRows->length();

		for (int i = 0; i < headerCount; ++i)
		{
			struct header * headerInstance = headerRows->get( i );

			printf("%-20s	%-30s \n", headerInstance->name, headerInstance->value);
			
		}

	}

	void add( char * name, char * value ) {

		header * headerInstance = new header();

		headerInstance->name 	= name;

		headerInstance->value	= value;

		this->headers->add( headerInstance );

	}

	void set( char * name, char * value ) {

		struct header * headerInstance = this->get( name );

		if( headerInstance == NULL ) {

			this->add( name, value );

		} else {

			int headerIndex	= this->getHeaderIndex( name );

			array * headers = this->headers;


			header * headerInstance = headers->get( headerIndex );

			headerInstance->value	= value;


		}

	}

	int getHeaderIndex( char * name ) {

		array * headers = this->headers;

		int count = headers->length();

		for (int i = 0; i < count; ++i)
		{
			
			header * headerInstance = headers->get( i );

			if( headerInstance->name == name ) {

				return i;

			}

		}

		return -1;

	}

	char * getValue( char * name ) {

		array * headers = this->headers;

		int count = headers->length();

		for (int i = 0; i < count; ++i)
		{
			
			header * headerInstance = headers->get( i );

			if( headerInstance->name == name ) {

				return headerInstance->value;

			}

		}

		return NULL;

	}

	header * get( char * name ) {

		array * headers = this->headers;

		int count = headers->length();

		for (int i = 0; i < count; ++i)
		{
			
			header * headerInstance = headers->get( i );

			if( headerInstance->name == name ) {

				return headerInstance;

			}

		}

		return NULL;

	}

}
