/***************************************************************************
                           clogfile.cpp  -  description
                             -------------------
    begin                : Sat Dec 14 2002
    copyright            : (C) 2002-2005 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "clogfile.h"

#include <time.h>
#include <stdio.h>

#include "cmutex.h"

/** */
CMutex CLogFile::m_LogFileMutex = CMutex();

/** */
CLogFile::CLogFile()
{
}

/** */
CLogFile::~CLogFile()
{
}

/** */
bool CLogFile::Write( CString file, eLogType /*type*/, CString message )
{
	bool res = false;
	char timestamp[23];
	struct tm * t;
	time_t ti;
	FILE * logfile;
	
	m_LogFileMutex.Lock();

	ti = time(0);
	t  = localtime(&ti);
	
	strftime(timestamp, sizeof(timestamp), "[%F.%H:%M:%S] ", t);
	
	// TODO: fix logfiles and add option to set logpath ...
/*
	if ( CConfig::Instance() )
	{
		file = CConfig:Instance()->GetLogPath() + file;
	}
*/
	if ( (logfile = fopen(file.Data(),"a")) != 0 )
	{
		if ( fwrite(timestamp,22,1,logfile) == 1 )
		{
			message += "\n";
			if ( fwrite(message.Data(),message.Length(),1,logfile) == 1 )
			{
				res = true;
			}
		}
		
		if ( fclose(logfile) != 0 )
		{
			res = false;
		}
	}

	m_LogFileMutex.UnLock();

	return res;
}
