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

*/

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

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

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


#include "ZTLogsListPage.h"
#include <QGraphicsProxyWidget>
#include "OutilZT.h"
#include "TrainLogFileMgr.h"
#include <QString>
#include <QTextCodec>
#include <QTextStream>
#include <QDebug>
#include <QFileDialog>



CZTLogsListPage::~CZTLogsListPage()
{

//    delete mListParsingTimer;
}

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

    mZTLogsTable = new QTableWidget(0,3);
	QGraphicsProxyWidget *TableProxy = new QGraphicsProxyWidget(this);
    TableProxy->setWidget(mZTLogsTable);
	TableProxy->setPos(3,20);
    TableProxy->resize(380,350);
    mZTLogsTable->resize(420,350);
    mZTLogsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    mZTLogsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    mZTLogsTable->clearContents();
    mZTLogsTable->setRowCount(0);
    mZTLogsTable->setHorizontalHeaderLabels(QStringList() << "Station" << "Début" << "Fin");
//	connect(mZTLogsTable,SIGNAL(cellClicked(int,int)),this,SLOT(LogsTableCellClicked(int,int)));
    connect(mZTLogsTable,SIGNAL(currentCellChanged(int,int,int,int)),this,SLOT(LogsTableCellSelected(int,int,int,int)));
    connect(mZTLogsTable,SIGNAL(cellDoubleClicked(int,int)),SLOT(TableDoubleClicked(int,int)));

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

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

    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 10/12" << "Montmorency 10/22" << "Côte Vertu" << "Saint-Michel");
    mStationsFilterComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    mStationsFilterComboBox->adjustSize();
    mStationsFilterComboBox->setMaxVisibleItems(15);
    connect(mStationsFilterComboBox,SIGNAL(activated(int)),this,SLOT(StationFilterSelected(int)));
}

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

void CZTLogsListPage::ButtonClicked(CTextButtonWidget *BtnPtr)
{
//    if(BtnPtr == mViewLogDataButton)
//	{
//		if(mLogMgrHandle->GetLogsCount() == 0)
//			return;

//        int cursel = mZTLogsTable->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 = mZTLogsTable->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);
//	}
}

unsigned int CZTLogsListPage::RefreshList()
{
    ClearTable();
    mProgramHandle->ShowZTLogFile("");

    QList<CZTLogFileInfo> *ZTLogsList = mZTLogFilesManager->GetZTLogsList();

    if(ZTLogsList->size() == 0)
        return RET_OK;

    mZTLogsTable->setRowCount(ZTLogsList->size());

    int CurRow = 0;
    for(int i = 0; i < ZTLogsList->size(); i++)
    {
        QString stationtext = mStationsFilterComboBox->currentText();
        if(ZTLogsList->at(i).mStationName == stationtext || stationtext == "Toutes")
        {
            QTableWidgetItem * NewItem = new QTableWidgetItem(ZTLogsList->at(i).mStationName);
            NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            NewItem->setData(Qt::UserRole,QVariant(i));
            mZTLogsTable->setItem(CurRow,0,NewItem);

            NewItem = new QTableWidgetItem(ZTLogsList->at(i).mStartDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
            NewItem->setData(Qt::UserRole,QVariant(i));
            NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            mZTLogsTable->setItem(CurRow,1,NewItem);

            NewItem = new QTableWidgetItem(ZTLogsList->at(i).mEndDateTime.toString("yyyy/MM/dd - hh:mm:ss"));
            NewItem->setData(Qt::UserRole,QVariant(i));
            NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
            mZTLogsTable->setItem(CurRow,2,NewItem);

            CurRow++;
        }
    }

    mZTLogsTable->setRowCount(CurRow);

    mZTLogsTable->resizeColumnsToContents();

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

    mZTLogsTable->setCurrentCell(0,0);
    LogsTableCellClicked(0,0);


	return RET_OK;

}

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

}

void CZTLogsListPage::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 CZTLogsListPage::LogsTableCellClicked(int row, int column)
{
	Q_UNUSED(column);

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


    QList<CZTLogFileInfo> *ZTLogsList = mZTLogFilesManager->GetZTLogsList();

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

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


    QFile *ZTLogFile = new QFile(ZTLogsList->at(ItemIndex).mZTLogFilePath);
    if(ZTLogFile)
    {
        ZTLogFile->open(QIODevice::ReadOnly | QIODevice::Text);
        QString str = ZTLogFile->readAll();

        ZTLogFile->close();

        delete ZTLogFile;

        mProgramHandle->ShowZTLogFile(str);
    }
}

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

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

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