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

    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 <ddwebcookie.h>
#include <ddbasetime.h>



const char* ddwebcookie::dd_cookie_data[] =
{
  /*
  	cookie_name=0,
		cookie_value=1,
    cookie_comment=3,
		cookie_expires=5,
		cookie_path=7,
 		cookie_site=9,
    cookie_secure=11,
    cookie_version=12,
    cookie_fieldsize=14
  */
	"name","",
	"Comment", "",	
  "expires","",
  "path","",	
  "domain","",
  "Secure","",
  "Version", "",  
	0
};


/**
	Default constructor.
*/

ddwebcookie::ddwebcookie()
: ddstringrow( dd_cookie_data )
{

}


/**
	Standard constructor.
	@param name the name(=key) of this cookie.
	@param value the value of this cookie.
	@see set_data()
*/


ddwebcookie::ddwebcookie( const ddstring& name, const ddstring& value )
: ddstringrow( dd_cookie_data )
{
	set_cookie_data( name, value );
}
  
  
/**
	Destructor.
*/


ddwebcookie::~ddwebcookie()
{
}



#define CHARBUFSIZE 40


/**
	@see www.netscape.com/newsref/std/cookie_spec.html
*/

void ddwebcookie::set_expires( size_t days )
{
	// FIX! Das gehört nach ddbasedate
	//size_t strftime(char *s, size_t max, const char *format,  const struct tm *tm);

	struct tm tmptime;
	char result[CHARBUFSIZE];
	time_t now = ::time(0);
	now += ddbasedate::SECS_PER_DAY * days;
  ::gmtime_r( &now, &tmptime );
  ::strftime( result, CHARBUFSIZE-1, "%a, %d-%b-%Y %H:%M:%S GMT", &tmptime );
	get_expires().assign( result );
}


/**
	Write the content of this cookie into the given buffer
	@see ddiobuffer
*/

void ddwebcookie::flush_data( ddiobuffer& buffer )
{
 	dump();
	bool first= true;
	for( size_t i=0; i<size()-1; i++ )
  {
		// send valid fields only
		if( !(*this)[++i].empty() )
		{
      if( !first )
				buffer.append( "; ", 2 );
      if( first )
				first = false;
			buffer.append( (*this)[i-1] );
			buffer.append( "=", 1 );
			buffer.append( (*this)[i] );

		}
	}
}



/**
	
*/

void ddwebcookie::set_cookie_data( const ddstring& name, const ddstring& value, int days, const ddstring& domain, const ddstring& path )
{
	get_name()  = name;
	get_value() = value;
	get_site()  = domain;
	get_path()  = path;		 
	get_expires() = "";
	if( days>0 )	
		set_expires( days );
	else if( days==0 )	
		get_expires() = "";
	else if( days<0 )	
		get_expires() = DDEXPIREDATE;
}
	
		
/**
	
*/

void ddwebcookie::dump() const
{
	for( size_t i=0; i<size()-1; i++ )
		// send valid fields only 
		if( !(*this)[++i].empty() )
			cout << (*this)[i-1] << "=" << (*this)[i] << ";" << endl;
}
	

