/***************************************************************************

    supportware
    Copyright (C) 2001-2008 by c.holzheuer
    c.holzheuer@sourceworx.org

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

***************************************************************************/


#include <ddwebcgi.h>


/**
	Baut die CGI-Daten auf, in dem der inputstring an den '&'s
	zerhackt wird.
*/

void ddwebcgi::create( const ddstring& src, bool doappend )
{
	if( !doappend )
		clear();

	size_t beg=0, endp=0;

	// ein trennzeichen, ein feld (ala otti)
	while ( beg < src.size() )
	{
		endp = src.find_first_of( "&", beg );
		if (endp == ddstring::npos)
			endp = src.size();
		add_entry( src.substr( beg,endp-beg ) );
		beg = endp + 1;
	}
}




/**
	Ein "key=Value" paar abspeichern, vorher unescapen und 
	'böse' Zeichen entfernen
*/

void ddwebcgi::add_entry( const ddstring& src )
{
	size_t pos = src.find('=');
	// Format error: leave
	if( pos == ddstring::npos )
		return;
	// empty field: add empty field		
	if( pos == src.size()-1 )		
	{
		(*this)[ src.substr(0,pos) ]= "";
		return;
	}
	ddstring result = src.substr( pos+1 );
	result.unescape().trim_evil();
	(*this)[ src.substr(0,pos) ] = result.trim();
}


/**
	Create a string of all entries.
	@see ddbaseobject
*/

ddstring ddwebcgi::to_string() const
{
	ddstring result;
	ddstringmap::const_iterator pos = begin();
	for( ; pos != end(); ++pos )
	{
		if( pos != begin() )
			result += "&";
		result += (*pos).first;
		result += "=";
		result += (*pos).second.dup().escape();
	}
	return result;
}

