//
// C++ Implementation: c6logger.cpp
//
// Description:
//
//
// Author: Giorgio A. <openc6@hotmail.com>, (C) 2005
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "c6logger.h"
#include <qstring.h>
#include <qdatetime.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextstream.h>
#include "c6settings.h"
#include "macroetc.h"

extern "C"
{
#include <stdarg.h>
}

static QString getCurrentTimeStr();

C6Logger::C6Logger():
        _homeDirPath (QDir::homeDirPath())
{}


C6Logger::~C6Logger()
{}


/*!
    \fn C6Logger::debugPrint(const char *who,const char *msg,...)
 */
void C6Logger::debugPrint(const char *who,const char *msg,...)
{
    if (C6Settings::getInstance().getProtoLog())
    {
        va_list ap;
        char *tmp_str = new char [strlen(who)+strlen(msg)+2];

        strncpy(tmp_str,who,strlen(who));
        tmp_str[strlen(who)]=' ';
        strncpy(tmp_str+strlen(who)+1,msg,strlen(msg));
        tmp_str[strlen(who)+strlen(msg)+1]=0;

        va_start( ap, tmp_str );
        vfprintf(stderr,tmp_str,ap);
        va_end( ap );
        fprintf( stderr, "\n" );
        delete [] tmp_str;
    }
}


/*!
    \fn C6Logger::logChatOnFile(QString const & nick,QString const & from,QString const & message)
 */
void C6Logger::logChatOnFile(QString const & nick,QString const & from, QString const & message)
{
    if (C6Settings::getInstance().getLog())
    {
        QString logid  = QDate::currentDate().toString(Qt::ISODate)+"-";
        QFile file(_homeDirPath+"/"+C6DIR+"/Log/"+logid+nick);
        QTextStream stream( &file );

        if (file.open(IO_WriteOnly | IO_Append))
        {
            stream << getCurrentTimeStr() << "  " << from << " - " << message << "\n";
            file.close();
        }
    }
}

/*!
    \fn C6Logger::logRoomOnFile(QString & room,QString & message)
 */
void C6Logger::logRoomOnFile(QString & room,QString & message)
{
    if (C6Settings::getInstance().getRoomLog())
    {
        QString logid  = QDate::currentDate().toString(Qt::ISODate)+"-";
        QFile file(_homeDirPath+"/"+C6DIR+"/RoomLog/"+logid+room);
        QTextStream stream( &file );

        if (file.open(IO_WriteOnly | IO_Append))
        {
            stream << getCurrentTimeStr() << " - " << message << "\n";
            file.close();
        }
    }
}

static QString getCurrentTimeStr()
{
    return(QTime::currentTime(Qt::LocalTime).toString());
}

/*!
    \fn C6Logger::logSystemMessage()
 */
void C6Logger::logSystemMessage(QString const & message)
{
    if (C6Settings::getInstance().getSysLog())
    {
        QString logid = "System-"+QDate::currentDate().toString(Qt::ISODate);
        QFile file(_homeDirPath+"/"+C6DIR+"/SysLog/"+logid);
        QTextStream stream( &file );

        logid = getCurrentTimeStr();

        if (file.open(IO_WriteOnly | IO_Append))
        {
            stream << logid << " " << message << "\n";
            file.close();
        }
    }
}
