/*******************************************************************************
*                                                                              *
* Société de Transports de Montréal.                                    	   *
* 2012                                                                         *
*                                                                              *
* Projet Zones Tests                                                           *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
/*
    Description:
	Page affichant la liste des passages de train.

*/

/* ************************************************************************** */
/* Revision:
### 20131021 JFM
    Verision d'origine.

### YYYMMDD Description du besoin ou du bug
    Description du changement.
 */

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


#include "LogsListPage.h"
#include <QGraphicsProxyWidget>
#include "Zonetest.h"
#include "TrainLogFileMgr.h"
#include <QString>
#include "ZTLog.h"


CLogsListPage::~CLogsListPage()
{
//    delete mListParsingTimer;
	delete mLogArchiverThread;
	delete mLogArchiverWorkerThread;
}

CLogsListPage::CLogsListPage(QGraphicsWidget *Parent)
{
	setParentItem(Parent);
	mProgramHandle = 0;
	mUSBDetected = false;
    mShowZT1Items = mShowZT2Items = mShowNoDetections = true;

	mBackgroundRect = new QGraphicsRectItem(boundingRect(), this);
	QBrush BackgroundBrush(QColor(245, 245, 255));
	mBackgroundRect->setBrush(BackgroundBrush);

	mCancelButton = new CTextButtonWidget("Fermer");
	mCancelButton->setParentItem(this);
	mCancelButton->setPos(810,550);
	connect(mCancelButton,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));

    mLogsTable = new QTableWidget(0,3);
	QGraphicsProxyWidget *TableProxy = new QGraphicsProxyWidget(this);
	TableProxy->setWidget(mLogsTable);
	TableProxy->setPos(3,20);
	TableProxy->resize(300,550);
	mLogsTable->resize(300,550);
    mLogsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    mLogsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    mLogsTable->setHorizontalHeaderLabels(QStringList() << "Date du passage" << "Décl." << "Type");
//	connect(mLogsTable,SIGNAL(cellClicked(int,int)),this,SLOT(LogsTableCellClicked(int,int)));
	connect(mLogsTable,SIGNAL(cellDoubleClicked(int,int)),SLOT(TableDoubleClicked(int,int)));
	//connect(mLogsTable,SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),this,SLOT(TableCurItemChanged(QTableWidgetItem*,QTableWidgetItem*)));
	connect(mLogsTable,SIGNAL(itemSelectionChanged()),this,SLOT(LogsTableCellSelected(/*int,int*/)));


	mSummaryText = new QGraphicsTextItem(this);
	QFont textfont;
	textfont.setPointSize(12);
	mSummaryText->setFont(textfont);
	mSummaryText->setPlainText("Statistiques du passage:");
	mSummaryText->setPos(350,20);

    QGraphicsProxyWidget *CheckBoxProxy = new QGraphicsProxyWidget(this);
	mShowZT1ItemsChkBx = new QCheckBox("Masquer ZT1");
    CheckBoxProxy->setWidget(mShowZT1ItemsChkBx);
    CheckBoxProxy->setPos(320,550);
    mShowZT1ItemsChkBx->setChecked(false);
    connect(mShowZT1ItemsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    CheckBoxProxy = new QGraphicsProxyWidget(this);
	mShowZT2ItemsChkBx = new QCheckBox("Masquer ZT2");
    CheckBoxProxy->setWidget(mShowZT2ItemsChkBx);
	//CheckBoxProxy->setPos(410,550);
	CheckBoxProxy->setPos(320,570);
    mShowZT2ItemsChkBx->setChecked(false);
    connect(mShowZT2ItemsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    CheckBoxProxy = new QGraphicsProxyWidget(this);
	mShowNoDetectionsChkBx = new QCheckBox("Seulement\ndéclenchements");
    CheckBoxProxy->setWidget(mShowNoDetectionsChkBx);
	CheckBoxProxy->setPos(450,550);
    mShowNoDetectionsChkBx->setChecked(false);
    connect(mShowNoDetectionsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    mListParsingTimer = new QTimer();
    connect(mListParsingTimer,SIGNAL(timeout()),this,SLOT(ParsingTimerExipred()));

	mUSBRefreshTimer = new QTimer();
	mUSBRefreshTimer->setSingleShot(false);
	connect(mUSBRefreshTimer,SIGNAL(timeout()),this,SLOT(CheckUSBKey()));

	QGraphicsRectItem *Frame = new QGraphicsRectItem(650,50,200,80,this);
	QPen FramePen;
	FramePen.setWidth(3);
	Frame->setPen(FramePen);

	QGraphicsTextItem *Label = new QGraphicsTextItem(this);
	Label->setPlainText("Sélection");
	Label->setPos(650,25);
	Label->setFont(textfont);

	mViewLogDataButton = new CTextButtonWidget("Voir");
	mViewLogDataButton->setParentItem(this);
	mViewLogDataButton->setPos(730,60);
	connect(mViewLogDataButton,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));

	mExportCSVLogButton = new CTextButtonWidget("Générer CSV");
	mExportCSVLogButton->setParentItem(this);
	mExportCSVLogButton->setPos(700,95);
	connect(mExportCSVLogButton,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));
    mExportCSVLogButton->hide();

	Label = new QGraphicsTextItem(this);
	Label->setPlainText("Sauvegarde des passages");
	Label->setPos(650,150);
	Label->setFont(textfont);

	Frame = new QGraphicsRectItem(650,175,200,80,this);
	Frame->setPen(FramePen);

	mArchiveFilesButton = new CTextButtonWidget("Archiver tout");
	mArchiveFilesButton->setParentItem(this);
	mArchiveFilesButton->setPos(700,185);
	connect(mArchiveFilesButton,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));
	mArchiveFilesButton->hide();

    mEraseFilesCheckbox = new QCheckBox("Conserver les passages");
	CheckBoxProxy = new QGraphicsProxyWidget(this);
	CheckBoxProxy->setWidget(mEraseFilesCheckbox);
	CheckBoxProxy->setPos(660,220);
	mEraseFilesCheckbox->hide();


	mInsertUSBKeyText = new QGraphicsTextItem("Veuillez insérer\nune clef USB",this);
	mInsertUSBKeyText->setPos(675,190);
	mInsertUSBKeyText->setFont(textfont);

	mLogArchiverWorkerThread = new CLogFileArchiverThread();
	mLogArchiverThread = new QThread();
	mLogArchiverWorkerThread->moveToThread(mLogArchiverThread);
	connect(mLogArchiverThread,SIGNAL(started()),mLogArchiverWorkerThread,SLOT(ArchiveLogs()));
	connect(mLogArchiverWorkerThread,SIGNAL(LogArchivingFinished()),this,SLOT(LogsArchivingFinished()));

}

unsigned int CLogsListPage::ArchiveAllFiles()
{
//	QString PathName = mUSBDrivePtr->GetDrivePath();
//	PathName += "/ArchiveLogZT_";
//	PathName += mProgramHandle->GetStationShortName();
//	PathName += QDateTime::currentDateTime().toString("_yyyyMMdd");
//	QDir TargetDir(PathName);

//	TargetDir.mkdir(PathName);	//If the directory does not exist, it will be created.

//	//copy files
//	QStringList LogFilters;
//	LogFilters << "*.bin" << "*.csv";
//	QDir LogDir("./Trains/");

//	int NbFiles = 0;
//	LogDir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
//	LogDir.setNameFilters(LogFilters);
//	LogDir.setSorting(QDir::Name);
//	for(int i = 0; i < LogDir.entryInfoList().size(); i++)
//	{
//		QString DestFileName = PathName;
//		DestFileName += "/";
//		DestFileName += LogDir.entryInfoList().at(i).fileName();
//		if(QFile::copy(LogDir.entryInfoList().at(i).absoluteFilePath(),DestFileName))
//		{
//			NbFiles++;
//		}
//	}

//	//Copy the ZTLog file each time.
//	QString DestFileName = PathName;
//	DestFileName += "/ZTLog.txt";
//	CZTLog::instance()->CopyLogFile(DestFileName,true);

//	system("sync");

//	CZTLog::instance()->AddLogString(QString().sprintf("%d fichiers de passage archivés dans le répertoire %s",NbFiles,PathName.toUtf8().data()),true);

//	if(mEraseFilesCheckbox->checkState() == Qt::Checked)
//	{
//		DeleteAllFiles();
//		system("sync");
//		mEraseFilesCheckbox->setChecked(false);
//	}


	mArchiveFilesButton->hide();
	mInsertUSBKeyText->setPlainText("Copie en cours\nN'enlevez pas la clef");
	mInsertUSBKeyText->show();
    mEraseFilesCheckbox->hide();

	mLogArchiverWorkerThread->SetPathInfo(mUSBDrivePtr->GetDrivePath(),mProgramHandle->GetStationShortName());

	QString PathName = mUSBDrivePtr->GetDrivePath();
	PathName += "/ArchiveLogZT_";
	PathName += mProgramHandle->GetStationShortName();
	PathName += QDateTime::currentDateTime().toString("_yyyyMMdd");
	QDir TargetDir(PathName);

	TargetDir.mkdir(PathName);	//If the directory does not exist, it will be created.

	QString DestFileName = PathName;
	DestFileName += "/ZTLog.txt";
	CZTLog::instance()->CopyLogFile(DestFileName,true);

	mLogArchiverThread->start();



	return RET_OK;
}

unsigned int CLogsListPage::DeleteAllFiles()
{
	QStringList LogFilters;
	LogFilters << "*.bin" << "*.csv";
	QDir LogDir("./Trains/");

	LogDir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
	LogDir.setNameFilters(LogFilters);
	LogDir.setSorting(QDir::Name);

	for(int i = 0; i < LogDir.entryInfoList().size(); i++)
	{
		QFile::remove(LogDir.entryInfoList().at(i).absoluteFilePath());
	}

	CZTLog::instance()->AddLogString("Tous les fichiers de passages ont été effacés",true);

	mLogMgrHandle->ParseLogs();
	RefreshList();

	return RET_OK;
}

void CLogsListPage::NewTrainLogFileSaved(QString Filename, bool Detection)
{
    Q_UNUSED(Filename)
    Q_UNUSED(Detection)
    RefreshList(true);
}

void CLogsListPage::resizeEvent(QGraphicsSceneResizeEvent *event)
{
	Q_UNUSED(event)
	mBackgroundRect->setRect(boundingRect());
}

void CLogsListPage::ButtonClicked(CTextButtonWidget *BtnPtr)
{
	if(BtnPtr == mCancelButton)
	{
        mSummaryText->setPlainText("Statistiques du passage:");
		hide();
	}
	else if(BtnPtr == mViewLogDataButton)
	{
		if(mLogMgrHandle->GetLogsCount() == 0)
			return;

		//int cursel = mLogsTable->currentItem()->data(Qt::UserRole).toInt();
		int cursel = GetCurSelectedItemIndexInTable();
		if(cursel == -1)
			return;

		CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);
		//qDebug("Sel: %d, Type : %d",cursel,Element->mZTLogType);
		mProgramHandle->LogViewRequest(mLogMgrHandle->LoadLogData(Element));
		mLogMgrHandle->FreeLogData(Element);


	}
	else if(BtnPtr == mExportCSVLogButton)
	{
		if(mLogMgrHandle->GetLogsCount() == 0)
			return;

		QString Filename;
		//int cursel = mLogsTable->currentItem()->data(Qt::UserRole).toInt();
		int cursel = GetCurSelectedItemIndexInTable();
		if(cursel == -1)
			return;

		CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);
		mLogMgrHandle->LoadLogData(Element);
		if(Element->mZTLogType == ZT1_LOG_TYPE)
		{
			CZT1LogElement *temp = (CZT1LogElement*)Element;
			Filename = temp->mLogFileName.replace("bin","csv");
			CTrainLogFileMgr::instance()->SaveCSVFile(Filename,&temp->mZTLogData,&temp->mFlags,&temp->mZTDetections,temp->mStationName);
		}
		else
		{
			CZT2LogElement *temp = (CZT2LogElement*)Element;
			Filename = temp->mLogFileName.replace("bin","csv");
			CTrainLogFileMgr::instance()->SaveCSVFile(Filename,&temp->mZTLogData,&temp->mZTDetections,temp->mStationName);
		}
		mLogMgrHandle->FreeLogData(Element);
	}
	else if(BtnPtr == mArchiveFilesButton)
	{
		ArchiveAllFiles();
	}
}

unsigned int CLogsListPage::BindPointers(CUSBDriveInterface *USBDriveIF)
{
	mUSBDrivePtr = USBDriveIF;
	mUSBRefreshTimer->start(1000);
	mLogArchiverWorkerThread->mLogMgrHandle = mLogMgrHandle;
	return RET_OK;
}

unsigned int CLogsListPage::RefreshList(bool KeepSelectedCell)
{

    QString SelectedCellText;
    if(KeepSelectedCell == true)
    {

        QList<QTableWidgetItem*> list = mLogsTable->selectedItems();

        if(list.size() == 0)
        {
            KeepSelectedCell = false;
        }

        for(int i = 0; i < list.size(); i++)
        {
            if(list.at(i)->column() == 0)
            {
                SelectedCellText = list.at(i)->text();
                qDebug("Selected cell text: %s",SelectedCellText.toAscii().data());
                break;
            }
        }

    }

    ClearTable();

    mShowZT1Items = (mShowZT1ItemsChkBx->checkState() == Qt::Unchecked);
    mShowZT2Items = (mShowZT2ItemsChkBx->checkState() == Qt::Unchecked);
    mShowNoDetections = (mShowNoDetectionsChkBx->checkState() == Qt::Unchecked);

    mLogsTable->setRowCount(mLogMgrHandle->GetLogsCount());

    if(mLogMgrHandle->GetLogsCount() == 0)
        return RET_OK;

    int CurRow = 0;

    QList<CLogElement*> *LogsList = mLogMgrHandle->GetLogsList();
    for(unsigned int i = 0; i < mLogMgrHandle->GetLogsCount(); i++)
    {
        if(LogsList->at(i)->mZTLogType == ZT1_LOG_TYPE && mShowZT1Items == true)
        {
            CZT1LogElement *ZT1LogElement = (CZT1LogElement*)LogsList->at(i);

            int NbDetections = ZT1LogElement->mZTDetections.size();
            if(mShowNoDetections == false && NbDetections == 0)
            {
            }
            else
            {
                QTableWidgetItem * NewItem = new QTableWidgetItem(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
				QVariant ID(QVariant::Int);
                ID.setValue(i);
				NewItem->setData(Qt::UserRole,ID);
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,0,NewItem);

                NewItem = new QTableWidgetItem(QString().sprintf("%d",NbDetections));
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,1,NewItem);

                NewItem = new QTableWidgetItem(QString().sprintf("ZT1"));
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,2,NewItem);

                CurRow++;
            }



        }
        else if(LogsList->at(i)->mZTLogType == ZT2_LOG_TYPE && mShowZT2Items == true)
        {
            CZT2LogElement *ZT2LogElement = (CZT2LogElement*)LogsList->at(i);

            int NbDetections = ZT2LogElement->mZTDetections.size();
            if(mShowNoDetections == false && NbDetections == 0)
            {
            }
            else
            {
                QTableWidgetItem * NewItem = new QTableWidgetItem(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
				QVariant ID(QVariant::Int);
				ID.setValue(i);
				NewItem->setData(Qt::UserRole,ID);
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,0,NewItem);

                NewItem = new QTableWidgetItem(QString().sprintf("%d",ZT2LogElement->mZTDetections.size()));
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,1,NewItem);

                NewItem = new QTableWidgetItem(QString().sprintf("ZT2"));
                NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                mLogsTable->setItem(CurRow,2,NewItem);

                CurRow++;
            }
        }
    }

    mLogsTable->setRowCount(CurRow);

    mLogsTable->setColumnWidth(0,150);
    mLogsTable->setColumnWidth(1,50);
    mLogsTable->setColumnWidth(2,50);

    mLogsTable->sortItems(0,Qt::DescendingOrder);

    if(KeepSelectedCell == true)
    {
        QList<QTableWidgetItem *> Items = mLogsTable->findItems(SelectedCellText,Qt::MatchFixedString);
        if(Items.size() != 0)
        {
            mLogsTable->setCurrentCell(Items.at(0)->row(),0);
            qDebug("Found cell text: %s",Items.at(0)->text().toAscii().data());
        }
        else
        {
            mLogsTable->setCurrentCell(0,0);
        }

    }
    else
    {
        mLogsTable->setCurrentCell(0,0);
    }
//	LogsTableCellClicked(0,0);


	return RET_OK;

}

void CLogsListPage::ClearTable()
{
	for(int Col = 0; Col < mLogsTable->columnCount(); Col++)
	{
		for(int Row = 0; Row < mLogsTable->rowCount(); Row++)
		{
			delete mLogsTable->item(Row,Col);
		}
	}
	mLogsTable->clearContents();
    mLogsTable->setRowCount(0);
}

//void CLogsListPage::LogsTableCellClicked(int row, int column)
//{
//	return;
//	Q_UNUSED(column);
//	Q_UNUSED(row);

////    int rowcount = mLogsTable->rowCount();
////    if(rowcount == 0)
////        return;

//////	qDebug("Selection : %d",row);
////	QList<CLogElement*> *LogsList = mLogMgrHandle->GetLogsList();

////	float MeanSpeed = 0.0;
////    QString Summary;
////    int ItemIndex = mLogsTable->item(row,0)->data(Qt::UserRole).toInt();
////	ShowItemSummary(LogsList->at(ItemIndex));
//}

void CLogsListPage::ShowItemSummary(CLogElement *Element)
{
	float MeanSpeed;
	QString Summary;
	if(Element->mZTLogType == ZT1_LOG_TYPE)
	{
//        //CZT1LogElement *ZT1LogElement = (CZT1LogElement*) LogsList->at(row);
		CZT1LogElement *ZT1LogElement = (CZT1LogElement*) Element;

		MeanSpeed = ZT1LogElement->mMeanSpeed;
        QString Problem = "Non";
        if(ZT1LogElement->mFlags.mIsProblematicPassage == 1)
        {
            Problem = "Oui";
        }


        QString Composition("Inconnue");
        if(ZT1LogElement->mFlags.mTrainCompo1 != 0) //if compo is valid, this will be != 0...
        {
            Composition = QString("%1 - %2 - %3").arg(ZT1LogElement->mFlags.mTrainCompo1).arg(ZT1LogElement->mFlags.mTrainCompo2).arg(ZT1LogElement->mFlags.mTrainCompo3);
        }
        QString TrainType = CZTData::GetTrainTypeString(ZT1LogElement->mTrainType);
        if(ZT1LogElement->mFlags.mModbusTrainType != MODBUS_CC_TRAIN_TYPE_INVALID_NOT_UPDATED)
        {
            TrainType = CZTData::GetModbusTrainTypeString(ZT1LogElement->mFlags.mModbusTrainType);
        }

        QString Iti("Principal");
        if(ZT1LogElement->mFlags.mZT1ITI == ZT_SECONDARY_ITI)
        {
            Iti = "Secondaire (10/22)";
        }

//        Summary.sprintf("Statistiques du passage:\n\nDate: %s\nHeure: %s\nTrain : %s\nNombre d'éléments: %d\nVitesse moyenne : %f mph\nPassage problématique: %s\n\nDéclenchements: \n",
//						ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd").toAscii().data(),
//						ZT1LogElement->mPassageDateTime.toString("hh:mm:ss").toAscii().data(),
//						CZTData::GetTrainTypeString(ZT1LogElement->mTrainType),
//						ZT1LogElement->mNbElements,
//                        MeanSpeed,
//                        Problem.toUtf8().data());

        Summary = QString("Statistiques du passage:\n\nDate: %1\nHeure: %2\nItinéraire : %3\nTrain : %4\nNombre d'éléments: %5\nComposition : %6\nPassage problématique: %7\n\nDéclenchements: \n")\
                        .arg(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd"))\
                        .arg(ZT1LogElement->mPassageDateTime.toString("hh:mm:ss"))\
                        .arg(Iti)\
                        .arg(TrainType)\
                        .arg(ZT1LogElement->mNbElements)\
                        .arg(Composition)\
                        .arg(Problem.toUtf8().data());

		if(ZT1LogElement->mZTDetections.size() >  0)
		{
			for(int i = 0; i < ZT1LogElement->mZTDetections.size(); i++)
			{
				QString temp;
				if(ZT1LogElement->mZTDetections.at(i)->mDetectionID == DETECTION_FN_DETECTION)
				{
					temp.sprintf("%s au bogie %d\n",CZTData::GetErrorString(ZT1LogElement->mZTDetections.at(i)->mDetectionID),ZT1LogElement->mZTDetections.at(i)->mRank);
				}
				else
				{
					temp.sprintf("%s au rang %d\n",CZTData::GetErrorString(ZT1LogElement->mZTDetections.at(i)->mDetectionID),ZT1LogElement->mZTDetections.at(i)->mRank);
				}
				Summary += temp;
				if(i >= MAX_DETECTION_LIST_NBR - 1)
				{
					temp = " -- Autres déclenchements non affichés --";
					Summary += temp;
					break;
				}
			}
		}
		else
			Summary += "Aucun déclenchement";
	}
	//else if(LogsList->at(row)->mZTLogType == ZT2_LOG_TYPE)
	else if(Element->mZTLogType == ZT2_LOG_TYPE)
	{
		//CZT2LogElement *ZT2LogElement = (CZT2LogElement*) LogsList->at(row);
		CZT2LogElement *ZT2LogElement = (CZT2LogElement*) Element;
        QString Problem = "Non";
        if(ZT2LogElement->mFlags.mIsProblematicPassage == 1)
        {
            Problem = "Oui";
        }

        Summary.sprintf("Statistiques du passage:\n\nDate: %s\nHeure: %s\nNombre d'éléments: %d\nPassage problématique: %s\n\n\n\nDéclenchements: \n",
						ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd").toAscii().data(),
						ZT2LogElement->mPassageDateTime.toString("hh:mm:ss").toAscii().data(),
                        ZT2LogElement->mNbElements,
                        Problem.toUtf8().data());

		if(ZT2LogElement->mZTDetections.size() >  0)
		{
			for(int i = 0; i < ZT2LogElement->mZTDetections.size(); i++)
			{
				QString temp;
				temp.sprintf("%s au rang %d\n",CZTData::GetErrorString(ZT2LogElement->mZTDetections.at(i)->mDetectionID),ZT2LogElement->mZTDetections.at(i)->mRank);
				Summary += temp;
				if(i >= MAX_DETECTION_LIST_NBR-1)
				{
					temp = " -- Autres déclenchements non affichés --";
					Summary += temp;
					break;
				}
			}
		}
		else
			Summary += "Aucun déclenchement";

	}
	mSummaryText->setPlainText(Summary);
}

void CLogsListPage::ParsingTimerExipred()
{
    if(mLogMgrHandle->ParseNextLog() == false)
    {
        mListParsingTimer->stop();
    }
    else
    {
        int CurRow = mLogsTable->rowCount();
        mLogsTable->setRowCount(CurRow+1);

        QList<CLogElement*> *LogsList = mLogMgrHandle->GetLogsList();
        //for(unsigned int i = 0; i < mLogMgrHandle->GetLogsCount(); i++)
        {
            if(LogsList->last()->mZTLogType == ZT1_LOG_TYPE && mShowZT1Items == true)
            {
                CZT1LogElement *ZT1LogElement = (CZT1LogElement*)LogsList->last();

                int NbDetections = ZT1LogElement->mZTDetections.size();
                if(mShowNoDetections == false && NbDetections == 0)
                {
                }
                else
                {
                    QTableWidgetItem * NewItem = new QTableWidgetItem(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                    NewItem->setData(Qt::UserRole,QVariant(LogsList->size()-1));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,0,NewItem);

                    NewItem = new QTableWidgetItem(QString().sprintf("%d",NbDetections));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,1,NewItem);

                    NewItem = new QTableWidgetItem(QString().sprintf("ZT1"));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,2,NewItem);
                }
            }
            else if(LogsList->last()->mZTLogType == ZT2_LOG_TYPE && mShowZT2Items == true)
            {
                CZT2LogElement *ZT2LogElement = (CZT2LogElement*)LogsList->last();

                int NbDetections = ZT2LogElement->mZTDetections.size();
                if(mShowNoDetections == false && NbDetections == 0)
                {
                }
                else
                {
                    QTableWidgetItem * NewItem = new QTableWidgetItem(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                    NewItem->setData(Qt::UserRole,QVariant(LogsList->size()-1));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,0,NewItem);

                    NewItem = new QTableWidgetItem(QString().sprintf("%d",ZT2LogElement->mZTDetections.size()));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,1,NewItem);

                    NewItem = new QTableWidgetItem(QString().sprintf("ZT2"));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,2,NewItem);
                }
            }
        }

//        mLogsTable->setRowCount(CurRow+1);

        mLogsTable->setColumnWidth(0,150);
        mLogsTable->setColumnWidth(1,50);
        mLogsTable->setColumnWidth(2,50);


        mLogsTable->sortItems(0);

        mListParsingTimer->start(20);

//        mLogsTable->setCurrentCell(0,0);
//        LogsTableCellClicked(0,0);
    }
}

void CLogsListPage::CheckUSBKey()
{
	if(mUSBDrivePtr->IsDriveDetected() != mUSBDetected)
	{
		mUSBDetected = mUSBDrivePtr->IsDriveDetected();

		if(mUSBDetected == true)
		{
			mInsertUSBKeyText->hide();
			mArchiveFilesButton->show();
            mEraseFilesCheckbox->setCheckState(Qt::Unchecked);
            mEraseFilesCheckbox->show();
		}
		else
		{
			mInsertUSBKeyText->setPlainText("Veuillez insérer\nune clef USB");
			mInsertUSBKeyText->show();
			mArchiveFilesButton->hide();
            mEraseFilesCheckbox->hide();
		}
	}

}

//Grab the mouse if the user clicks outside buttons
void CLogsListPage::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
	Q_UNUSED(event)
}
void CLogsListPage::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	Q_UNUSED(event)
}
void CLogsListPage::CheckBoxClicked(int state)
{
    Q_UNUSED(state)
    RefreshList();
}

void CLogsListPage::TableDoubleClicked(int row, int col)
{
    Q_UNUSED(col)
	Q_UNUSED(row)
    ButtonClicked(mViewLogDataButton);
}
//void CLogsListPage::TableCurItemChanged(QTableWidgetItem *Current, QTableWidgetItem *Prev)
//{
//	int rowcount = mLogsTable->rowCount();
//	if(rowcount == 0)
//		return;

//	if(Prev == Current)
//		return;

//	QList<CLogElement*> *LogsList = mLogMgrHandle->GetLogsList();
//	int Selection = Current->data(Qt::UserRole).toInt();
//	CLogElement *SelectedElement = LogsList->at(Selection);
//	ShowItemSummary(SelectedElement);
////	qDebug("Changed %d",Selection);

//}

void CLogsListPage::LogsTableCellSelected(/*int row, int col*/)
{
	int Selection = GetCurSelectedItemIndexInTable();

	if(Selection == -1)
		return;

	QList<CLogElement*> *LogsList = mLogMgrHandle->GetLogsList();
	CLogElement *SelectedElement = LogsList->at(Selection);
	ShowItemSummary(SelectedElement);
}

int CLogsListPage::GetCurSelectedItemIndexInTable()
{
	QList<QTableWidgetItem*> list = mLogsTable->selectedItems();

	if(list.size() == 0)
		return - 1;

	int Selection = -1;
	for(int i = 0; i < list.size(); i++)
	{
		if(list.at(i)->column() == 0)
		{
			Selection = list.at(i)->data(Qt::UserRole).toInt();
			break;
		}
	}

	return Selection;
}

void CLogsListPage::LogsArchivingFinished()
{

//	CZTLog::instance()->DeleteLogFile();

    if(mEraseFilesCheckbox->checkState() == Qt::Unchecked)
    {
        mLogMgrHandle->DeleteErrorLogs();
    }

    //The "sync" command has been moved in the thread instead of pausing the watchdog...

//    The file syncing can take a lot of time (the "sync" command syncs ALL of the file system).
//    So we must disable the watchdog to avoid a computer reboot.
//    mProgramHandle->PauseInternalWatchdog();
//    system("sync");
//    mProgramHandle->ResumeInternalWatchdog();


	RefreshList();
	mLogArchiverThread->quit();
    if(mEraseFilesCheckbox->checkState() == Qt::Unchecked)
    {
        mProgramHandle->ResetTriggerCount();
        mProgramHandle->ResetNbPassages();
    }
	mInsertUSBKeyText->hide();
	mArchiveFilesButton->show();
    mEraseFilesCheckbox->show();
    CZTLog::instance()->DeleteLogFile();
}




////// Thread implementation //////////////

CLogFileArchiverThread::CLogFileArchiverThread()
{
	mDrivePath = "";
}

void CLogFileArchiverThread::SetPathInfo(QString DrivePath,QString StationName)
{
	mDrivePath = DrivePath;
	mStationName = StationName;
}

void CLogFileArchiverThread::ArchiveLogs()
{

	QString PathName = mDrivePath;
	PathName += "/ArchiveLogZT_";
	PathName += mStationName;
	PathName += QDateTime::currentDateTime().toString("_yyyyMMdd");
	QDir TargetDir(PathName);

	TargetDir.mkdir(PathName);	//If the directory does not exist, it will be created.

	//copy files
	QStringList LogFilters;
	LogFilters << "*.bin" << "*.csv";
	QDir LogDir("./Trains/");

	int NbFiles = 0;
	LogDir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
	LogDir.setNameFilters(LogFilters);
	LogDir.setSorting(QDir::Name);
	for(int i = 0; i < LogDir.entryInfoList().size(); i++)
	{
		QString DestFileName = PathName;
		DestFileName += "/";
		DestFileName += LogDir.entryInfoList().at(i).fileName();
		if(QFile::copy(LogDir.entryInfoList().at(i).absoluteFilePath(),DestFileName))
		{
			NbFiles++;
		}
	}

	///JFM: Is it dangerous to access these from the thread ?
//	CZTLog::instance()->DeleteLogFile();
//	mLogMgrHandle->DeleteErrorLogs();
    /// Moved outside of threads

    system("sync");

	CZTLog::instance()->AddLogString(QString().sprintf("%d fichiers de passage archivés dans le répertoire %s",NbFiles,PathName.toUtf8().data()),true);

	emit LogArchivingFinished();
}
