// This file is part of the Coral project.
// Please read the copyright notice in the LICENSE file.

#include "c_time.h"
#include <locale>
#include <string>
#include <time.h>
#include <coral/lib/assert.h>
#include <sstream>

NAMESPACE_BEGIN(coral);
NAMESPACE_BEGIN(io);

NAMESPACE_BEGIN();

static const char timeformat[] = "%a, %d %b %Y %H:%M:%S %z";

NAMESPACE_END();


std::string getCurrentRFC822Time() {
	time_t curtime;
	std::time(&curtime);
	struct tm the_tm;
	localtime_r(&curtime, &the_tm);
	std::ostringstream s;
	/* This is necessary!
	 * It tells the stream @s to use the clocale
	 * when outputting various data, such as
	 * weekdays etc.
	 */
	s.imbue(clocale);

	typedef std::ostreambuf_iterator<char, 
		std::char_traits<char> > iter;
	// I'm not sure if this requires clocale. Can't hurt though?
	const std::time_put<char, iter>& timeput = 
	  std::use_facet<std::time_put<char, iter> >(clocale);
	iter begin(s);
	timeput.put(begin, s, ' ', &the_tm,
		    timeformat, timeformat + sizeof(timeformat) - 1);

	return s.str();
}

NAMESPACE_END();
NAMESPACE_END();

