/*******************************************************************************
*                                                                              *
* Société de Transports de Montréal.                                    	   *
* 2012                                                                         *
*                                                                              *
* Projet Zones Tests                                                           *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
/*
    Description:
    Cette classe permet de créer un fichier log.

*/

/* ************************************************************************** */
/* Revision:
### 20121219 JFM
    Verision d'origine.
    
### YYYYMMDD Description du besoin ou du bug
    Description du changement.
 */

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

#include "ZTLog.h"
#include <QDateTime>
#include <QString>
#include <QTextCodec>
#include "EngLog.h"
#include <QTextStream>

//singleton instantiation
CZTLog CZTLog::mSingleton;

CZTLog::CZTLog():
	mZTLogFile(NULL)
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    mLogBuffer.clear();
    mLogBufferToEngLog = false;
    mProgramHandle = 0;
}

CZTLog::~CZTLog()
{
	if(mZTLogFile)
    {
        mZTLogFile->close();
		delete mZTLogFile;
    }
}

void CZTLog::Init()
{
    QString FileName;
    FileName = "./LOG/LogZT.txt";

    mZTLogFile = new QFile(FileName);
    if(mZTLogFile)
    {
        mZTLogFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);

        QString temp;
        mZTLogFile->write("\n\n");
        AddLogString(temp.sprintf("********************************************************************"));
        AddLogString(temp.sprintf("Démarrage du logiciel ZT le %s à %s",QDateTime::currentDateTime().date().toString("yyyy-MM-dd").toAscii().data(),QDateTime::currentDateTime().time().toString("hh:mm:ss").toAscii().data()));
        AddLogString(temp.sprintf("********************************************************************"));
    }
}

void CZTLog::AddLogString(QString string,bool AddToEngLog)
{
//	qDebug(string.toUtf8().data());

	if(mZTLogFile == NULL)
        return;

	if(mZTLogFile->isOpen() == false)
        return;

    if(AddToEngLog)
        CEngLog::instance()->AddLogString(string,1);

        if(string.at(string.length()-1) != '\n')
            string.append('\n');

        if(string.length() > 1)
			string.prepend(QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz :     ").toAscii().data());

        mZTLogFile->write(string.toUtf8());



//#ifndef WINDOWS_OS
//        system("sync");
//#endif

}

void CZTLog::AddBufferString(QString string, bool AddToEngLog, bool ForceWrite)
{
    if(string.at(string.length()-1) != '\n')
        string.append('\n');

    if(string.length() > 1)
        string.prepend(QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz :     ").toAscii().data());

    mLogBuffer += string;

    if(AddToEngLog)
        mLogBufferToEngLog = true;

    if(ForceWrite)
        mForceWriteBuffer = true;
}

void CZTLog::ClearBufferString()
{
    mLogBuffer.clear();
    mLogBufferToEngLog = false;
    mForceWriteBuffer = false;
}

void CZTLog::WriteBufferToLog()
{
    if(mLogBufferToEngLog)
    {
        CEngLog::instance()->WriteFormattedString(mLogBuffer);
    }

    mZTLogFile->write(mLogBuffer.toUtf8());

    ClearBufferString();
}

unsigned int CZTLog::CopyLogFile(QString Dest,bool DeleteIfPresent)
{
	if(QFile::exists(Dest))
	{
		if(DeleteIfPresent == false)
			return RET_ERROR;

		QFile::remove(Dest);
	}
	mZTLogFile->close();
	QFile::copy("./LOG/LogZT.txt",Dest);
	mZTLogFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);

	return RET_OK;
}

unsigned int CZTLog::DeleteLogFile()
{
	mZTLogFile->remove();
	delete mZTLogFile;

	mZTLogFile = new QFile("./LOG/LogZT.txt");
	if(mZTLogFile)
	{
		mZTLogFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);

		QString temp;
		mZTLogFile->write("\n\n");
		AddLogString(temp.sprintf("********************************************************************"));
		AddLogString(temp.sprintf("Création d'un nouveau fichier LOG après sa destruction le %s à %s",QDateTime::currentDateTime().date().toString("yyyy-MM-dd").toAscii().data(),QDateTime::currentDateTime().time().toString("hh:mm:ss").toAscii().data()));
		AddLogString(temp.sprintf("********************************************************************"));
	}
	mZTLogFile->flush();


    //Insert the current ZT settings in the log file.
    if(mProgramHandle != 0)
    {
        mProgramHandle->LogZTSettingsRequest(true);
    }




	return RET_OK;
}

QString CZTLog::GetEntireLogFile()
{
	mZTLogFile->close();
	mZTLogFile->open(QIODevice::ReadOnly | QIODevice::Text);
	QTextStream Stream(mZTLogFile);

	QString str = Stream.readAll();

	mZTLogFile->close();
	mZTLogFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);

	return str;
}
