// Local configuration
#include "config.h"

// Implementation
#include "SysLogMono.hpp"

// STDC++
#include <cassert>

// C: Syslog
#include <syslog.h>

// Local
#include "Misc.hpp"


namespace UI {
namespace Util {

SysLogMono::SysLogMono(std::string const & ident, int option, int facility)
	:std::streambuf()
	,std::ostream((std::streambuf *)this)
	,ident_(ident)
	,buf_("")
	,level_(LOG_DEBUG)
{
	::openlog(ident_.c_str(), option, facility);
}

SysLogMono::~SysLogMono(void)
{
	::closelog();
}

int SysLogMono::overflow(int c)
{
	if (c == '\n' || c == '\0')
	{
		::syslog(level_, "%s", buf_.c_str());
		buf_ = "";
	}
	else
	{
		buf_ += (char)c;
	}
	return c;
}

SysLogMono & SysLogMono::operator()(int level)
{
	level_ = level;
	return *this;
}

SysLogMonoSingleton::SysLogMonoSingleton(std::string const & ident, int option, int facility)
{
	assert(singleton_ == 0);
	singleton_ = new SysLogMono(ident, option, facility);
}

SysLogMonoSingleton::~SysLogMonoSingleton()
{
	assert(singleton_);
	delete singleton_;
	singleton_ = 0;
}

SysLogMono & SysLogMonoSingleton::log(int level)
{
	assert(singleton_);
	return (*singleton_)(level);
}

SysLogMono * SysLogMonoSingleton::singleton_(0);

}}
