/*******************************************************************************
*                                                                              *
* 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 "OutilZT.h"
#include "TrainLogFileMgr.h"
#include <QString>
#include <QTextCodec>
#include <QTextStream>
#include <QDebug>
#include <QFileDialog>
#include <QDir>
#include <QFileInfo>
#include "TrainLogFileMgr.h"
#include <QApplication>
#include <QFile>


CLogsListPage::~CLogsListPage()
{
//    delete mListParsingTimer;
    delete mLogsTable;
}

CLogsListPage::CLogsListPage(QGraphicsWidget *Parent)
{
    //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	setParentItem(Parent);
	mProgramHandle = 0;
    mStationFilter.clear();

    QFile PathSource("SourcePath.txt");
    mNetworkBasePath = NETWORK_LOGS_BASE_PATH;
    if(PathSource.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QString Path;
       do
        {
            Path = QString(PathSource.readLine());
            if(Path.contains('#') == false)
            {
                mNetworkBasePath = Path.chopped(1);
                break;
            }
        }
        while(!PathSource.atEnd());
    }

    mLogsTable = new QTableWidget(0,4);
    mLogListTableProxy = new QGraphicsProxyWidget(this);
    mLogListTableProxy->setWidget(mLogsTable);
    mLogListTableProxy->setPos(3,20);
    mLogListTableProxy->resize(380,350);
    mLogsTable->resize(380,350);
    mLogsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    mLogsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    mLogsTable->clearContents();
    mLogsTable->setRowCount(0);
    mLogsTable->setHorizontalHeaderLabels(QStringList() << "Date du passage" << "Station" << "Décl." << "Type");
//	connect(mLogsTable,SIGNAL(cellClicked(int,int)),this,SLOT(LogsTableCellClicked(int,int)));
    connect(mLogsTable,SIGNAL(currentCellChanged(int,int,int,int)),this,SLOT(LogsTableCellSelected(int,int,int,int)));
    connect(mLogsTable,SIGNAL(cellDoubleClicked(int,int)),SLOT(TableDoubleClicked(int,int)));

    mLogListTableProxy->hide();

    mLogsTreeProxy = new QGraphicsProxyWidget(this);
    mLogFilesTree = new QTreeWidget;
    mLogsTreeProxy->setWidget(mLogFilesTree);
    mLogFilesTree->setColumnCount(3);
     mLogFilesTree->resize(590,350);
     mLogFilesTree->setHeaderLabels(QStringList() << "Passage" << "Décl" << "Zone" << "Compo");
     connect(mLogFilesTree,SIGNAL(itemExpanded(QTreeWidgetItem*)),this,SLOT(LogsTreeItemExpanded(QTreeWidgetItem*)));
     connect(mLogFilesTree,SIGNAL(itemSelectionChanged()),this,SLOT(LogsTreeItemSelected()));
     connect(mLogFilesTree,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(LogsTreeItemDoubleClicked(QTreeWidgetItem*)));
     connect(mLogFilesTree,SIGNAL(itemCollapsed(QTreeWidgetItem*)),this,SLOT(LogsTreeItemCollapsed(QTreeWidgetItem*)));
     mLogFilesTree->setSortingEnabled(true);

 //   mLogsTreeProxy->hide();

     QTreeWidgetItem* TopStationItem;
     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Angrignon");
     CTreeItemInfo *ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) + "ANG";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(0,TopStationItem);

     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Berri-UQAM");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) + "BUQ4";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(1,TopStationItem);

     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Côte-Vertu");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
    ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "CVRT";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(2,TopStationItem);


     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"H-Beaugrand");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "HBGR";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(3,TopStationItem);


     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Longueuil");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "LONG";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(4,TopStationItem);


     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Montmorency");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "MMO";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(5,TopStationItem);


     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"Snowdon");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "SNW5";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(6,TopStationItem);


     TopStationItem = new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr));
     TopStationItem->setText(0,"St-Michel");
     ItemInfo = new CTreeItemInfo;
     ItemInfo->TreeItemType = TREE_ITEM_STATION_TYPE;
     ItemInfo->TreeItemPath = QString(mNetworkBasePath) +  "SMIC";
     TopStationItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
     TopStationItem->addChild(new QTreeWidgetItem(QStringList() << ""));
     mLogFilesTree->insertTopLevelItem(7,TopStationItem);

     mLogFilesTree->sortByColumn(0,Qt::AscendingOrder);


	mSummaryText = new QGraphicsTextItem(this);
	QFont textfont;
	textfont.setPointSize(12);
	mSummaryText->setFont(textfont);
    mSummaryText->setPlainText("Passage:");
    mSummaryText->setPos(3,370);

    QGraphicsProxyWidget *WidgetProxy = new QGraphicsProxyWidget(this);
    mShowZT1ItemsChkBx = new QCheckBox("ZT1");
    WidgetProxy->setWidget(mShowZT1ItemsChkBx);
    WidgetProxy->setPos(190,450);
    mShowZT1ItemsChkBx->setChecked(true);
    connect(mShowZT1ItemsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowZT2ItemsChkBx = new QCheckBox("ZT2");
    WidgetProxy->setWidget(mShowZT2ItemsChkBx);
    //WidgetProxy->setPos(410,550);
    WidgetProxy->setPos(250,450);
    mShowZT2ItemsChkBx->setChecked(true);
    connect(mShowZT2ItemsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowNoDetectionsChkBx = new QCheckBox("Sans décl.");
    WidgetProxy->setWidget(mShowNoDetectionsChkBx);
    WidgetProxy->setPos(300,450);
    mShowNoDetectionsChkBx->setChecked(true);
    connect(mShowNoDetectionsChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));




    int x = 190, y = 480;
    int xSpacing = 100, ySpacing = 30;

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowFNChkBx = new QCheckBox("Frotteur");
    WidgetProxy->setWidget(mShowFNChkBx);
    WidgetProxy->setPos(x,y+ySpacing);
    mShowFNChkBx->setChecked(true);
    connect(mShowFNChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowCountChkBx = new QCheckBox("Comptage");
    WidgetProxy->setWidget(mShowCountChkBx);
    WidgetProxy->setPos(x+xSpacing,y+ySpacing);
    mShowCountChkBx->setChecked(true);
    connect(mShowCountChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowPGChkBx = new QCheckBox("P. Guidage");
    WidgetProxy->setWidget(mShowPGChkBx);
    WidgetProxy->setPos(x+(xSpacing),y+(ySpacing*2));
    mShowPGChkBx->setChecked(true);
    connect(mShowPGChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowPPChkBx = new QCheckBox("P. Porteur");
    WidgetProxy->setWidget(mShowPPChkBx);
    WidgetProxy->setPos(x,y+(ySpacing*2));
    mShowPPChkBx->setChecked(true);
    connect(mShowPPChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowMPM10ChkBx = new QCheckBox("MPM10");
    WidgetProxy->setWidget(mShowMPM10ChkBx);
    WidgetProxy->setPos(x,y);
    mShowMPM10ChkBx->setChecked(true);
    connect(mShowMPM10ChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowMRChkBx = new QCheckBox("MR63/73");
    WidgetProxy->setWidget(mShowMRChkBx);
    WidgetProxy->setPos(x+(xSpacing),y);
    mShowMRChkBx->setChecked(true);
    connect(mShowMRChkBx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mShowProblematicTrainsChkbx = new QCheckBox("Passage Problématique");
    WidgetProxy->setWidget(mShowProblematicTrainsChkbx);
    WidgetProxy->setPos(x,y+(ySpacing*3));
    mShowProblematicTrainsChkbx->setChecked(true);
    connect(mShowProblematicTrainsChkbx,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    WidgetProxy = new QGraphicsProxyWidget(this);
    mLoadTreeLogDetails = new QCheckBox("Charger détails");
    WidgetProxy->setWidget(mLoadTreeLogDetails);
    WidgetProxy->setPos(190,390);
    mLoadTreeLogDetails->setChecked(true);
    connect(mLoadTreeLogDetails,SIGNAL(stateChanged(int)),this,SLOT(CheckBoxClicked(int)));

    mTreeLoadingStatusLabel = new QGraphicsTextItem(this);
    mTreeLoadingStatusLabel->setPlainText("");
    mTreeLoadingStatusLabel->setPos(190,395);
    mTreeLoadingStatusLabel->hide();

    QGraphicsTextItem *Label = new QGraphicsTextItem(this);
    Label->setPlainText("Station:");
    Label->setPos(190,418);

    WidgetProxy = new QGraphicsProxyWidget(this);
    mProtectLogChkBx = new QCheckBox("Passage protégé");
    WidgetProxy->setWidget(mProtectLogChkBx);
    WidgetProxy->setPos(190,390);
    mProtectLogChkBx->setChecked(false);
    connect(mProtectLogChkBx,SIGNAL(clicked()),this,SLOT(ProtectLogCheckBoxClicked()));
    mProtectLogChkBx->setEnabled(false);

    WidgetProxy = new QGraphicsProxyWidget(this);
    mStationsFilterComboBox = new QComboBox();
    WidgetProxy->setWidget(mStationsFilterComboBox);
    WidgetProxy->setPos(250,420);
    mStationsFilterComboBox->insertItems(0,QStringList() << "Toutes" << "Angrignon" << "Snowdon" << "Henri Bourassa" << "Honoré Beaugrand" << "Longueuil" << "Berri UQAM" << "Montmorency" << "Montmorency (10/12)" << "Montmorency (10/22)" << "Côte Vertu" << "Saint-Michel" << "Du Collège");
    mStationsFilterComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    mStationsFilterComboBox->adjustSize();
    mStationsFilterComboBox->setMaxVisibleItems(15);
    connect(mStationsFilterComboBox,SIGNAL(activated(int)),this,SLOT(StationFilterSelected(int)));

    mViewZTLogBtn = new CPushButton(this,"./Images/log.png",false,0);
    mViewZTLogBtn->resize(50,50);
    mViewZTLogBtn->setPos(400,375);
    connect(mViewZTLogBtn,SIGNAL(clicked(CPushButton*)),this,SLOT(ViewZTLogBtnClicked(CPushButton*)));

    mSaveCSVLogBtn = new CPushButton(this,"./Images/csv.png",false,0);
    mSaveCSVLogBtn->resize(50,50);
    mSaveCSVLogBtn->setPos(400,450);
    connect(mSaveCSVLogBtn,SIGNAL(clicked(CPushButton*)),this,SLOT(SaveCSVLogBtnClicked(CPushButton*)));

    mDeleteFileButton = new CPushButton(this,"./Images/file_delete.png",false,0);
    mDeleteFileButton->resize(50,50);
    mDeleteFileButton->setPos(400,525);
    connect(mDeleteFileButton,SIGNAL(clicked(CPushButton*)),this,SLOT(DeleteSelectedLog(CPushButton*)));

    mLogsTreeMode = new CPushButton(this,"./Images/directory.png",false,0);
    mLogsTreeMode->resize(50,50);
    mLogsTreeMode->setPos(475,375);
    connect(mLogsTreeMode,SIGNAL(clicked(CPushButton*)),this,SLOT(TreeLogsViewModeSelected(CPushButton*)));

    mLogsTableMode = new CPushButton(this,"./Images/database.png",false,0);
    mLogsTableMode->resize(50,50);
    mLogsTableMode->setPos(475,450);
    connect(mLogsTableMode,SIGNAL(clicked(CPushButton*)),this,SLOT(TableLogsViewModeSelected(CPushButton*)));

    mSaveCSVLogBtn->hide();
    mDeleteFileButton->hide();

//    TreeLogsViewModeSelected(mLogsTreeMode);
    TableLogsViewModeSelected(mLogsTableMode);





}

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

void CLogsListPage::ButtonClicked(CTextButtonWidget *BtnPtr)
{
    if(BtnPtr == mViewLogDataButton)
	{
		if(mLogMgrHandle->GetLogsCount() == 0)
			return;
        int cursel = mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt();
        CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);
        mProgramHandle->LogViewRequest(mLogMgrHandle->LoadLogData(Element),this);
		mLogMgrHandle->FreeLogData(Element);

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

		QString Filename;
        int cursel = mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt();
        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);
	}
}

void CLogsListPage::EnableEngineeringMode()
{
    mSaveCSVLogBtn->hide();
    mDeleteFileButton->hide();
    mProtectLogChkBx->setEnabled(false);
}

unsigned int CLogsListPage::RefreshList()
{
    ClearTable();

    bool ShowZT1Items = (mShowZT1ItemsChkBx->checkState() == Qt::Checked);
    bool ShowZT2Items = (mShowZT2ItemsChkBx->checkState() == Qt::Checked);
    bool ShowNoDetections = (mShowNoDetectionsChkBx->checkState() == Qt::Checked);

    bool ShowPPDetections = (mShowPPChkBx->checkState() == Qt::Checked);
    bool ShowPGDetections = (mShowPGChkBx->checkState() == Qt::Checked);
    bool ShowCountDetections = (mShowCountChkBx->checkState() == Qt::Checked);
    bool ShowFNDetections = (mShowFNChkBx->checkState() == Qt::Checked);
    bool ShowMRTrains = (mShowMRChkBx->checkState() == Qt::Checked);
    bool ShowMPM10Trains = (mShowMPM10ChkBx->checkState() == Qt::Checked);
    bool ShowProblematicTrains = (mShowProblematicTrainsChkbx->checkState() == Qt::Checked);


    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 && ShowZT1Items == true)
        {
            CZT1LogElement *ZT1LogElement = (CZT1LogElement*)LogsList->at(i);
            QString stationtext = mStationsFilterComboBox->currentText();
            if((ZT1LogElement->mStationName == mStationsFilterComboBox->currentText() || mStationsFilterComboBox->currentText() == "Toutes") &&
               ((ShowMPM10Trains == true) || (ShowMPM10Trains == false && ZT1LogElement->mTrainType != TRAIN_TYPE_MPM10)) &&
               ((ShowMRTrains == true) || (ShowMRTrains == false && ZT1LogElement->mTrainType != TRAIN_TYPE_MR63_MR73)) &&
                (ShowProblematicTrains == true || (ShowProblematicTrains == false && ZT1LogElement->mFlags.mIsProblematicPassage != 1)))
            {

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

                    NewItem = new QTableWidgetItem(ZT1LogElement->mStationName);
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,1,NewItem);

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

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

                    CurRow++;
                }
                else if(ShowNoDetections == false && NbDetections == 0)
                {
                }
                else
                {
                    bool FilterItem = true;

                    for(int trig = 0; trig < NbDetections; trig++)
                    {
                        quint32 DetectionID = ZT1LogElement->mZTDetections.at(trig)->mDetectionID;

                        if((ShowCountDetections == true && DetectionID == DETECTION_MAGNETIC_SENSOR_COUNT) ||
                           (ShowFNDetections == true && DetectionID == DETECTION_FN_DETECTION) ||
                           (ShowPGDetections == true && DetectionID == DETECTION_PG_DETECTION) ||
                           (ShowPPDetections == true && (DetectionID == DETECTION_PPI_DETECTION || DetectionID == DETECTION_PPE_DETECTION)) ||
                           (DetectionID == DETECTION_PEQ1_DETECTION) ||
                           (DetectionID == DETECTION_PEQ2_DETECTION))
                        {
                            FilterItem = false;
                            break;
                        }

                    }

                    if(FilterItem == false)
                    {
                        QTableWidgetItem * NewItem = new QTableWidgetItem(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                        NewItem->setData(Qt::UserRole,QVariant(i));
                        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                        mLogsTable->setItem(CurRow,0,NewItem);

                        NewItem = new QTableWidgetItem(ZT1LogElement->mStationName);
                        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                        mLogsTable->setItem(CurRow,1,NewItem);

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

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

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

            if((ZT2LogElement->mStationName == mStationsFilterComboBox->currentText() || mStationsFilterComboBox->currentText() == "Toutes") &&
               (ShowProblematicTrains == true || (ShowProblematicTrains == false && ZT2LogElement->mFlags.mIsProblematicPassage != 1)))
            {
                int NbDetections = ZT2LogElement->mZTDetections.size();
                if(ShowNoDetections == true && NbDetections == 0)
                {
                    QTableWidgetItem * NewItem = new QTableWidgetItem(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                    NewItem->setData(Qt::UserRole,QVariant(i));
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,0,NewItem);

                    NewItem = new QTableWidgetItem(ZT2LogElement->mStationName);
                    NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                    mLogsTable->setItem(CurRow,1,NewItem);

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

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

                    CurRow++;
                }
                else if(ShowNoDetections == false && NbDetections == 0)
                {
                }
                else
                {
                    bool FilterItem = true;

                    for(int trig = 0; trig < NbDetections; trig++)
                    {
                        quint32 DetectionID = ZT2LogElement->mZTDetections.at(trig)->mDetectionID;

                        if((ShowCountDetections == true && DetectionID == DETECTION_ZT2_MAGNETIC_SENCOR_COUNT) ||
                           (ShowPPDetections == true && (DetectionID == DETECTION_ZT2_PPI_DETECTION || DetectionID == DETECTION_ZT2_PPE_DETECTION)))
                        {
                            FilterItem = false;
                            break;
                        }
                    }

                    if(FilterItem == false)
                    {
                        QTableWidgetItem * NewItem = new QTableWidgetItem(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                        NewItem->setData(Qt::UserRole,QVariant(i));
                        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                        mLogsTable->setItem(CurRow,0,NewItem);

                        NewItem = new QTableWidgetItem(ZT2LogElement->mStationName);
                        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                        mLogsTable->setItem(CurRow,1,NewItem);

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

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

                        CurRow++;
                    }
                }
            }
        }
    }

    mLogsTable->setRowCount(CurRow);

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

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

    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->item(Row,Col) = 0;
		}
    }
    mLogsTable->setRowCount(0);
	mLogsTable->clearContents();

}

void CLogsListPage::LogsTableCellSelected( int row, int col, int prevrow, int prevcol)
{
    Q_UNUSED(prevrow)
    Q_UNUSED(prevcol)


    if(row < 0 || col < 0)
        return;

    LogsTableCellClicked(row,col);
}

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

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

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

//	float MeanSpeed = 0.0;
//    QString Summary;

    if(mLogsTable->item(row,0) == 0)
        return;

    int ItemIndex = mLogsTable->item(row,0)->data(Qt::UserRole).toInt();

    UpdateSummaryText(LogsList->at(ItemIndex));
//    if(LogsList->at(ItemIndex)->mZTLogType == ZT1_LOG_TYPE)
//    {
////        //CZT1LogElement *ZT1LogElement = (CZT1LogElement*) LogsList->at(row);
//		CZT1LogElement *ZT1LogElement = (CZT1LogElement*) LogsList->at(ItemIndex);

//        if(ZT1LogElement->mFileProtected == true)
//        {
//            mProtectLogChkBx->setCheckState(Qt::Checked);
//        }
//        else
//        {
//            mProtectLogChkBx->setCheckState(Qt::Unchecked);
//        }

//        QString Problem = "N/A";
//        if(ZT1LogElement->mFlags.mIsProblematicPassage == 1)
//        {
//            Problem = "OUI";
//        }
//        else if(ZT1LogElement->mFlags.mIsProblematicPassage == 0)
//        {
//            Problem = "NON";
//        }
//		MeanSpeed = ZT1LogElement->mMeanSpeed;

//        QString TrainType = CZTData::GetModbusTrainTypeString(ZT1LogElement->mFlags.mModbusTrainType);
//        if(TrainType == "Inconnu")
//        {
//            TrainType = CZTData::GetTrainTypeString(ZT1LogElement->mTrainType);
//        }

//        QString TrainCompo = "Non Disponible";
//      //  if(!((ZT1LogElement->mFlags.mTrainCompo1 == 0) && (ZT1LogElement->mFlags.mTrainCompo2 == 0) && (ZT1LogElement->mFlags.mTrainCompo3 == 0)))
//        {
//            TrainCompo = QString("%1-%2-%3").arg(ZT1LogElement->mFlags.mTrainCompo1)\
//                                            .arg(ZT1LogElement->mFlags.mTrainCompo2)
//                                            .arg(ZT1LogElement->mFlags.mTrainCompo3);
//        }

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

//        Summary = QString("Passage:\n\nDate: %1\nHeure: %2\nItinéraire: %7\nZone Test : ZT1\nTrain : %3\nCompo: %6\nNombre d'éléments: %4\nProblématique: %5\n\n\nDéclenchements: \n")\
//                    .arg(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd"))\
//                    .arg(ZT1LogElement->mPassageDateTime.toString("hh:mm:ss"))\
//                    .arg(TrainType)\
//                    .arg(ZT1LogElement->mNbElements)\
//                    .arg(Problem)
//                    .arg(TrainCompo)
//                    .arg(Iti);
////        Summary.sprintf("Passage:\n\nDate: %s\nHeure: %s\nZone Test : ZT1\nTrain : %s\nNombre d'éléments: %d\nProblématique: %s\n\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,
////                        Problem.toAscii().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(LogsList->at(ItemIndex)->mZTLogType == ZT2_LOG_TYPE)
//    {
//        //CZT2LogElement *ZT2LogElement = (CZT2LogElement*) LogsList->at(row);
//        CZT2LogElement *ZT2LogElement = (CZT2LogElement*) LogsList->at(ItemIndex);

//        if(ZT2LogElement->mFileProtected == true)
//        {
//            mProtectLogChkBx->setCheckState(Qt::Checked);
//        }
//        else
//        {
//            mProtectLogChkBx->setCheckState(Qt::Unchecked);
//        }

//        QString Problem = "N/A";
//        if(ZT2LogElement->mFlags.mIsProblematicPassage == 1)
//        {
//            Problem = "OUI";
//        }
//        else if(ZT2LogElement->mFlags.mIsProblematicPassage == 0)
//        {
//            Problem = "NON";
//        }
////        Summary.sprintf("Statistiques du passage:\n\nDate: %s\nHeure: %s\nZone Test: ZT2\nNombre d'éléments: %d\nProblé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.toAscii().data());

//        QString TrainType = CZTData::GetModbusTrainTypeString(ZT2LogElement->mFlags.mModbusTrainType);

//        QString TrainCompo = "Non Disponible";
//        if(ZT2LogElement->mFlags.mTrainCompo1 != 0)
//        {
//            TrainCompo = QString("%1-%2-%3").arg(ZT2LogElement->mFlags.mTrainCompo1)\
//                                            .arg(ZT2LogElement->mFlags.mTrainCompo2)
//                                            .arg(ZT2LogElement->mFlags.mTrainCompo3);
//        }

//        Summary = QString("Passage:\n\nDate: %1\nHeure: %2\nZone Test : ZT2\nTrain : %3\nCompo: %6\nNombre d'éléments: %4\nProblématique: %5\n\n\nDéclenchements: \n")\
//                    .arg(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd"))\
//                    .arg(ZT2LogElement->mPassageDateTime.toString("hh:mm:ss"))\
//                    .arg(TrainType)\
//                    .arg(ZT2LogElement->mNbElements)\
//                    .arg(Problem)
//                    .arg(TrainCompo);

//        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);

    CLogElement* Element = mLogMgrHandle->LoadLogData(LogsList->at(ItemIndex));
    mProgramHandle->LogViewRequest(Element,this);
    mLogMgrHandle->FreeLogData(Element);

}

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

        if(ZT1LogElement->mFileProtected == true)
        {
            mProtectLogChkBx->setCheckState(Qt::Checked);
        }
        else
        {
            mProtectLogChkBx->setCheckState(Qt::Unchecked);
        }

        QString Problem = "N/A";
        if(ZT1LogElement->mFlags.mIsProblematicPassage == 1)
        {
            Problem = "OUI";
        }
        else if(ZT1LogElement->mFlags.mIsProblematicPassage == 0)
        {
            Problem = "NON";
        }
        MeanSpeed = ZT1LogElement->mMeanSpeed;

        QString TrainType = CZTData::GetModbusTrainTypeString(ZT1LogElement->mFlags.mModbusTrainType);
        if(TrainType == "Inconnu")
        {
            TrainType = CZTData::GetTrainTypeString(ZT1LogElement->mTrainType);
        }

        QString TrainCompo = "Non Disponible";
      //  if(!((ZT1LogElement->mFlags.mTrainCompo1 == 0) && (ZT1LogElement->mFlags.mTrainCompo2 == 0) && (ZT1LogElement->mFlags.mTrainCompo3 == 0)))
        {
            TrainCompo = QString("%1-%2-%3").arg(ZT1LogElement->mFlags.mTrainCompo1)\
                                            .arg(ZT1LogElement->mFlags.mTrainCompo2)
                                            .arg(ZT1LogElement->mFlags.mTrainCompo3);
        }

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

        Summary = QString("Passage:\n\nDate: %1\nHeure: %2\nItinéraire: %7\nZone Test : ZT1\nTrain : %3\nCompo: %6\nNombre d'éléments: %4\nProblématique: %5\n\n\nDéclenchements: \n")\
                    .arg(ZT1LogElement->mPassageDateTime.toString("yyyy/MM/dd"))\
                    .arg(ZT1LogElement->mPassageDateTime.toString("hh:mm:ss"))\
                    .arg(TrainType)\
                    .arg(ZT1LogElement->mNbElements)\
                    .arg(Problem)
                    .arg(TrainCompo)
                    .arg(Iti);
//        Summary.sprintf("Passage:\n\nDate: %s\nHeure: %s\nZone Test : ZT1\nTrain : %s\nNombre d'éléments: %d\nProblématique: %s\n\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,
//                        Problem.toAscii().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;

        if(ZT2LogElement->mFileProtected == true)
        {
            mProtectLogChkBx->setCheckState(Qt::Checked);
        }
        else
        {
            mProtectLogChkBx->setCheckState(Qt::Unchecked);
        }

        QString Problem = "N/A";
        if(ZT2LogElement->mFlags.mIsProblematicPassage == 1)
        {
            Problem = "OUI";
        }
        else if(ZT2LogElement->mFlags.mIsProblematicPassage == 0)
        {
            Problem = "NON";
        }
//        Summary.sprintf("Statistiques du passage:\n\nDate: %s\nHeure: %s\nZone Test: ZT2\nNombre d'éléments: %d\nProblé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.toAscii().data());

        QString TrainType = CZTData::GetModbusTrainTypeString(ZT2LogElement->mFlags.mModbusTrainType);

        QString TrainCompo = "Non Disponible";
        if(ZT2LogElement->mFlags.mTrainCompo1 != 0)
        {
            TrainCompo = QString("%1-%2-%3").arg(ZT2LogElement->mFlags.mTrainCompo1)\
                                            .arg(ZT2LogElement->mFlags.mTrainCompo2)
                                            .arg(ZT2LogElement->mFlags.mTrainCompo3);
        }

        Summary = QString("Passage:\n\nDate: %1\nHeure: %2\nZone Test : ZT2\nTrain : %3\nCompo: %6\nNombre d'éléments: %4\nProblématique: %5\n\n\nDéclenchements: \n")\
                    .arg(ZT2LogElement->mPassageDateTime.toString("yyyy/MM/dd"))\
                    .arg(ZT2LogElement->mPassageDateTime.toString("hh:mm:ss"))\
                    .arg(TrainType)\
                    .arg(ZT2LogElement->mNbElements)\
                    .arg(Problem)
                    .arg(TrainCompo);

        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);
    return RET_OK;
}

void CLogsListPage::StationFilterSelected(int Index)
{
    Q_UNUSED(Index);
    RefreshList();
}

void CLogsListPage::ViewZTLogBtnClicked(CPushButton *btn)
{
    if(mLogsTable->rowCount() == 0)
        return;

    int cursel = mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt();
    CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);
    QString FilePath;
    QDateTime PassageDateTime;

    if(Element->mZTLogType == ZT1_LOG_TYPE)
    {
        CZT1LogElement* log = (CZT1LogElement*)Element;
        FilePath = log->mLogFileName;
        PassageDateTime = log->mPassageDateTime;
    }
    else
    {
        CZT2LogElement* log = (CZT2LogElement*)Element;
        FilePath = log->mLogFileName;
        PassageDateTime = log->mPassageDateTime;
    }

    QFileInfo FileDir(FilePath);
    QString ZTLogFilePath = FileDir.absolutePath();
    ZTLogFilePath += "/ZTLog.txt";
    if(QFileInfo(ZTLogFilePath).exists() == false)
    {
        ZTLogFilePath = FileDir.absolutePath();
        ZTLogFilePath += "/LogZT.txt";
    }

    int line =0;
    QFile *LogFile = new QFile(ZTLogFilePath);
    if(LogFile)
    {
        if(LogFile->open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::Unbuffered) == true)
        {
            QString LogText(LogFile->readAll());

            //Try to find the line corresponding to the selected train passage in the log
            QDateTime DateTimeLine1,DateTimeLine2;

            QTextStream strm(&LogText);
            strm.seek(0);

            bool finished = false;
            QString temp;
            do
            {
                temp = strm.readLine();
                line++;

                if(strm.atEnd())
                    break;
            }
            while(temp.length() < 10);

            QStringList parts = temp.split(" : ");
            QString LineText,DateString;
            LineText.clear();

            if(PassageDateTime > DateTimeLine1)
            {
                if(parts.size() != 0)
                {
                    DateString = parts.at(0);
                    DateTimeLine1 = QDateTime::fromString(DateString,"yyyy/MM/dd - hh:mm:ss.zzz");
                    while(!finished)
                    {
                        temp = strm.readLine();
                        line++;
                        if(temp.length() > 10)
                        {
                            parts = temp.split(" : ");
                            if(parts.size() != 0)
                            {
                                DateString = parts.at(0);
                                DateTimeLine2 = QDateTime::fromString(DateString,"yyyy/MM/dd - hh:mm:ss.zzz");

                                if(PassageDateTime >= DateTimeLine1 && PassageDateTime <= DateTimeLine2)
                                {
                                    LineText = parts.at(0);
                                    finished = true;
                                }
                            }

                        }
                        else
                        {
                            if(strm.atEnd())
                                finished = true;
                        }
                        DateTimeLine1 = DateTimeLine2;
                    }
                }
            }

            mProgramHandle->ShowZTLogRequest(LogText,LineText);
            LogFile->close();
        }
        delete LogFile;
    }
}

void CLogsListPage::SaveCSVLogBtnClicked(CPushButton *)
{
    if(mLogsTable->rowCount() == 0)
        return;

    QString Filename;
    int cursel = mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt();
    CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);
    mLogMgrHandle->LoadLogData(Element);
    if(Element->mZTLogType == ZT1_LOG_TYPE)
    {
        CZT1LogElement *temp = (CZT1LogElement*)Element;
        QString dummy;
        dummy = temp->mLogFileName;//.replace("bin","csv");
        Filename = dummy.replace("bin","csv");

        QString CSVFileName = QFileDialog::getSaveFileName(0,"Exporter .csv",Filename,tr("CSV (*.csv)"));

        CTrainLogFileMgr::instance()->SaveCSVFile(CSVFileName,&temp->mZTLogData,&temp->mFlags,&temp->mZTDetections,temp->mStationName);
    }
    else
    {
        CZT2LogElement *temp = (CZT2LogElement*)Element;
        QString dummy;
        dummy = temp->mLogFileName;
        Filename = dummy.replace("bin","csv");

        QString CSVFileName = QFileDialog::getSaveFileName(0,"Exporter .csv",Filename,tr("CSV (*.csv)"));

        CTrainLogFileMgr::instance()->SaveCSVFile(CSVFileName,&temp->mZTLogData,&temp->mZTDetections,temp->mStationName);
    }
    mLogMgrHandle->FreeLogData(Element);
}
void CLogsListPage::DeleteSelectedLog(CPushButton *)
{
    if(mLogsTable->rowCount() == 0)
        return;

    int SelRow = mLogsTable->selectedItems().at(0)->row();
    int SelCol = mLogsTable->selectedItems().at(0)->column();

    mLogMgrHandle->DeleteLog(mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt());
    RefreshList();

    mLogsTable->setCurrentCell(SelRow,SelCol);
}

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

void CLogsListPage::ProtectLogCheckBoxClicked()
{
    int state = mProtectLogChkBx->checkState();
    int cursel = mLogsTable->selectedItems().at(0)->data(Qt::UserRole).toInt();
    CLogElement* Element = mLogMgrHandle->GetLogsList()->at(cursel);

    if(state == Qt::Checked)
    {
        if(mProgramHandle->SetLogProtection(true,Element,this) == RET_ERROR)
        {
            mProtectLogChkBx->setCheckState(Qt::Unchecked);
        }
    }
    else
    {
        if(mProgramHandle->SetLogProtection(false,Element,this) == RET_ERROR)
        {
            mProtectLogChkBx->setCheckState(Qt::Checked);
        }
    }
}

void CLogsListPage::TableDoubleClicked(int row, int col)
{
    Q_UNUSED(col)
	Q_UNUSED(row)
   // ButtonClicked(mViewLogDataButton);
}

void CLogsListPage::LogsTreeItemExpanded(QTreeWidgetItem *item)
{
    CTreeItemInfo *ItemInfo = (CTreeItemInfo*)item->data(0,Qt::UserRole).value<void*>();
    if(ItemInfo)
    {

        switch(ItemInfo->TreeItemType)
        {
            case TREE_ITEM_STATION_TYPE:
            {
                qDebug("%s",qPrintable(ItemInfo->TreeItemPath));

                //delete all tree
                qDebug("Deleting tree");
                while(item->childCount() > 0)  //delete directories branch
                {
                    QTreeWidgetItem *DirItem = item->takeChild(0);

                    while(DirItem->childCount() > 0)   //delete logs list
                    {
                        QTreeWidgetItem *LogItem = DirItem->takeChild(0);
                        CTreeItemInfo *Info = (CTreeItemInfo*)LogItem->data(0,Qt::UserRole).value<void*>();
                        if(Info)
                            delete Info;
                       // DirItem->removeChild(LogItem);
                    }

                    CTreeItemInfo *Info = (CTreeItemInfo*)DirItem->data(0,Qt::UserRole).value<void*>();
                    if(Info)
                        delete Info;

                  //  item->removeChild(DirItem);
                }

                qDebug("Tree deleted.  Populating data");
                CTreeItemInfo *Info = (CTreeItemInfo*)item->data(0,Qt::UserRole).value<void*>();
                if(Info)
                {
                    PopulateDirectoriesTreeBranch(item,Info->TreeItemPath);
                }
                else
                {
                    qDebug("Invalid path in station tree item...");
                }

                mLogFilesTree->resizeColumnToContents(0);

                break;
            }
            case TREE_ITEM_DIR_TYPE:
            {

                 qDebug("Deleting %d log items",item->childCount());
                while(item->childCount() > 0)  //delete log items
                {
                    QTreeWidgetItem *LogItem = item->takeChild(0);
                    CTreeItemInfo *Info = (CTreeItemInfo*)LogItem->data(0,Qt::UserRole).value<void*>();
                    if(Info)
                        delete Info;

                    delete LogItem;
                    //item->removeChild(LogItem);
                }

                qDebug("Logs deleted.  Populating data");
                CTreeItemInfo *Info = (CTreeItemInfo*)item->data(0,Qt::UserRole).value<void*>();
                if(Info)
                {
                    PopulateLogFilesTreeBranch(item,Info->TreeItemPath);
                }
                else
                {
                    qDebug("Invalid path in station tree item...");
                }

                qDebug("Data populated...");
                mLogFilesTree->resizeColumnToContents(0);
                break;
            }
            case TREE_ITEM_LOGFILE_TYPE:
            {
                break;
            }
        }
    }
}

void CLogsListPage::LogsTreeItemCollapsed(QTreeWidgetItem *item)
{

    if(item->parent())
    {
        mLogFilesTree->setCurrentItem(item->parent());
    }

    CTreeItemInfo *ItemInfo = (CTreeItemInfo*)item->data(0,Qt::UserRole).value<void*>();
    if(ItemInfo)
    {

        switch(ItemInfo->TreeItemType)
        {
            case TREE_ITEM_STATION_TYPE:
            {
                qDebug("%s",qPrintable(ItemInfo->TreeItemPath));

                //delete all tree
                qDebug("Deleting %d tree items",item->childCount());
                while(item->childCount() > 0)  //delete directories branch
                {
                    QTreeWidgetItem *DirItem = item->takeChild(0);

                    qDebug("Deleting %d logs items",DirItem->childCount());
                    while(DirItem->childCount() > 0)   //delete logs list
                    {
       //                 qDebug("Taking child");
                        QTreeWidgetItem *LogItem = DirItem->takeChild(0);
                        CTreeItemInfo *Info = (CTreeItemInfo*)LogItem->data(0,Qt::UserRole).value<void*>();
        //                qDebug("Deleting info");
                        if(Info)
                        {
      //                      qDebug("delete..");
                            delete Info;
                        }
     //                   qDebug("Tree item deleted");
                    }
                    CTreeItemInfo *Info = (CTreeItemInfo*)DirItem->data(0,Qt::UserRole).value<void*>();
                    if(Info)
                        delete Info;

//                    item->removeChild(DirItem);
                }

                qDebug("Tree deleted.");
                item->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item

                mLogFilesTree->resizeColumnToContents(0);

                break;
            }
            case TREE_ITEM_DIR_TYPE:
            {

                qDebug("Deleting %d log items",item->childCount());
                while(item->childCount() > 0)  //delete log items
                {
   //                 qDebug("Taking child");
                    QTreeWidgetItem *LogItem = item->takeChild(0);
                    CTreeItemInfo *Info = (CTreeItemInfo*)LogItem->data(0,Qt::UserRole).value<void*>();
   //                 qDebug("Deleting info");
                    if(Info)
                    {
 //                      qDebug("delete..");
                        delete Info;
                    }
 //                   qDebug("Tree item deleted");

                    delete LogItem;
                }

                qDebug("Logs deleted.");
                item->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item

                mLogFilesTree->resizeColumnToContents(1);
                break;
            }
            case TREE_ITEM_LOGFILE_TYPE:
            {
                break;
            }
        }
    }
}
int CLogsListPage::PopulateDirectoriesTreeBranch(QTreeWidgetItem *parent, QString Path)
{
    QDir Directory(Path);
    QFileInfoList DirList = Directory.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot);
    if(DirList.isEmpty())
    {
        parent->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item
    }
    else
    {
        for(int i = 0; i < DirList.size(); i++)
        {
            QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList() << DirList.at(i).fileName());
            CTreeItemInfo* ItemInfo = new CTreeItemInfo;
            ItemInfo->TreeItemType = TREE_ITEM_DIR_TYPE;
            ItemInfo->TreeItemPath = DirList.at(i).absoluteFilePath();
            NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
            NewDirItem->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item
            parent->addChild(NewDirItem);
        }
    }
}

int CLogsListPage::PopulateLogFilesTreeBranch(QTreeWidgetItem *parent, QString Path)
{
    QDir Directory(Path);
    QFileInfoList DirList = Directory.entryInfoList(QDir::Files|QDir::NoDotAndDotDot);
    bool ShowZT1Items = (mShowZT1ItemsChkBx->checkState() == Qt::Checked);
    bool ShowZT2Items = (mShowZT2ItemsChkBx->checkState() == Qt::Checked);
    bool ShowNoDetections = (mShowNoDetectionsChkBx->checkState() == Qt::Checked);
    bool LoadLogDetails = (mLoadTreeLogDetails->checkState() == Qt::Checked);

    float LoadingPercent = 0.0;
    int Size;

    if(DirList.isEmpty())
    {
        parent->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item
    }
    else
    {
        Size = DirList.size();
        for(int i = 0; i < Size; i++)
        {
            LoadingPercent = (float)(i+1)/(float)Size;
            LoadingPercent *= 100;
            mTreeLoadingStatusLabel->setPlainText(QString("Chargement:%1\%").arg(LoadingPercent));

       //     QApplication::processEvents();
            CTreeItemInfo* ItemInfo = new CTreeItemInfo;
            ItemInfo->TreeItemType = TREE_ITEM_LOGFILE_TYPE;
            ItemInfo->TreeItemPath = DirList.at(i).filePath();

            QStringList ItemData;
            if(DirList.at(i).suffix() == "bin")
            {
                if(LoadLogDetails == true)
                {
                    unsigned int ret;
                    CLogElement* Element = CTrainLogFileMgr::instance()->OpenTrainLog(ItemInfo->TreeItemPath,ret);
                    if(ret == RET_OK)
                    {
                        if(Element->mZTLogType == ZT1_LOG_TYPE && ShowZT1Items == true)
                        {
                            CZT1LogElement *ZT1Element = (CZT1LogElement*)Element;
                            if(!(ShowNoDetections == false && ZT1Element->mZTDetections.size() == 0))
                            {
                                ItemData.append(ZT1Element->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                                ItemData.append(QString("%1").arg(ZT1Element->mZTDetections.size()));
                                ItemData.append("ZT1");
                                ItemData.append(QString("%1-%2-%3").arg(ZT1Element->mFlags.mTrainCompo1).arg(ZT1Element->mFlags.mTrainCompo2).arg(ZT1Element->mFlags.mTrainCompo3));
                                QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList(ItemData));
                                NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
                                parent->addChild(NewDirItem);
                            }
                        }
                        else if(Element->mZTLogType == ZT2_LOG_TYPE && ShowZT2Items == true)
                        {
                            CZT2LogElement *ZT2Element = (CZT2LogElement*)Element;
                            if(!(ShowNoDetections == false && ZT2Element->mZTDetections.size() == 0))
                            {
                                ItemData.append(ZT2Element->mPassageDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
                                ItemData.append(QString("%1").arg(ZT2Element->mZTDetections.size()));
                                ItemData.append("ZT2");
                                ItemData.append(QString("%1-%2-%3").arg(ZT2Element->mFlags.mTrainCompo1).arg(ZT2Element->mFlags.mTrainCompo2).arg(ZT2Element->mFlags.mTrainCompo3));
                                QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList(ItemData));
                                NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
                                parent->addChild(NewDirItem);
                            }

                        }
                        delete Element;
                    }

                    else
                    {
                        ItemData.append(DirList.at(i).baseName());
                        QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList(ItemData));
                        NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
                        parent->addChild(NewDirItem);
                    }
                }
                else
                {

                    QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList() << DirList.at(i).baseName());
                    NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
                    parent->addChild(NewDirItem);
                }
            }
            else if(DirList.at(i).suffix() == "txt")
            {
                QTreeWidgetItem *NewDirItem = new QTreeWidgetItem(QStringList() << DirList.at(i).fileName());
                NewDirItem->setData(0,Qt::UserRole,QVariant::fromValue((void*)ItemInfo));
                parent->addChild(NewDirItem);
            }
            else
            {
                delete ItemInfo;
            }

            if(parent->childCount() == 0)
            {
                parent->addChild(new QTreeWidgetItem(QStringList() << "VIDE"));  //add an empty item
            }


        }
    }
}

void CLogsListPage::LogsTreeItemSelected()
{
    QTreeWidgetItem* Selection = mLogFilesTree->selectedItems().at(0);
    if(Selection)
    {
        CTreeItemInfo *Info = (CTreeItemInfo*)Selection->data(0,Qt::UserRole).value<void*>();
        if(Info)
        {
            if(Info->TreeItemType == TREE_ITEM_LOGFILE_TYPE)
            {
                QFileInfo FileInfo(Info->TreeItemPath);
                if(FileInfo.suffix() == "bin")
                {
                    unsigned int ret;
                    CLogElement* Element = CTrainLogFileMgr::instance()->OpenTrainLog(Info->TreeItemPath,ret,0,true);
                    if(ret == RET_OK)
                    {UpdateSummaryText(Element);
                        mProgramHandle->LogViewRequest(Element,this);
                        mLogMgrHandle->FreeLogData(Element);
                    }
                }
            }

        }
    }
}

void CLogsListPage::TableLogsViewModeSelected(CPushButton *Btb)
{
    mLogListTableProxy->show();
    mLogsTreeProxy->hide();

    mShowFNChkBx->show();
    mShowCountChkBx->show();
    mShowPGChkBx->show();
    mShowPPChkBx->show();
    mShowMPM10ChkBx->show();
    mShowMRChkBx->show();
    mShowProblematicTrainsChkbx->show();
    mStationsFilterComboBox->show();
    mViewZTLogBtn->show();
    mProtectLogChkBx->show();
    mLoadTreeLogDetails->hide();

}

void CLogsListPage::TreeLogsViewModeSelected(CPushButton *Btn)
{
    mLogListTableProxy->hide();
    mLogsTreeProxy->show();

    mShowFNChkBx->hide();
    mShowCountChkBx->hide();
    mShowPGChkBx->hide();
    mShowPPChkBx->hide();
    mShowMPM10ChkBx->hide();
    mShowMRChkBx->hide();
    mShowProblematicTrainsChkbx->hide();
    mStationsFilterComboBox->hide();
    mViewZTLogBtn->hide();
    mProtectLogChkBx->hide();
    mLoadTreeLogDetails->show();
}

void CLogsListPage::LogsTreeItemDoubleClicked(QTreeWidgetItem *item)
{
    CTreeItemInfo *Info = (CTreeItemInfo*)item->data(0,Qt::UserRole).value<void*>();
    if(Info)
    {
        if(Info->TreeItemType == TREE_ITEM_LOGFILE_TYPE)
        {
            QFileInfo FileInfo(Info->TreeItemPath);
            if(FileInfo.suffix() == "txt")
            {
                QFile *LogFile = new QFile(FileInfo.filePath());
                if(LogFile)
                {
                    if(LogFile->open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::Unbuffered) == true)
                    {
                        QString LogText(LogFile->readAll());
                        mProgramHandle->ShowZTLogRequest(LogText,0,-1);
                        LogFile->close();
                    }
                    delete LogFile;
                }
            }
        }
    }
}
