/*******************************************************************************
*                                                                              *
* Société de Transports de Montréal.                                    	   *
* 2012                                                                         *
*                                                                              *
* Projet Zones Tests                                                           *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
/*
    Description:
    Page offrant différentes option pour l'entretien de la ZT

*/

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

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

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


#include "MaintenancePage.h"
#include <QPainter>
#include "GlobalDefine.h"
#include <QDialog>
#include <QMainWindow>
#include "Zonetest.h"
#include <QDateTime>
#include <QFont>
#include <QGraphicsProxyWidget>
#include "ZTData.h"
#include <QMessageBox>
#include "ZTLog.h"
#include "ZTData.h"
#include "ZTconfigmgr.h"


CMaintenancePage::CMaintenancePage(QGraphicsWidget *Parent)
{
	Q_UNUSED(Parent)

    bool IsModbusEnabled = CZTConfigMgr::instance()->GetModbusCCEnabled();

	mProgramHandle = 0;

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

    QGraphicsTextItem *Title = new QGraphicsTextItem("Entretien de la Zone Tests",this);
	QFont font;
	font.setPointSize(18);
	Title->setFont(font);
	Title->setPos(40,10);


	mMaintenanceActivationBtn = new CToggleButtonWidget("./Images/Slider_Green.png","./Images/Slider_Red.png",this);
	mMaintenanceActivationBtn->setPos(45,65);
	mMaintenanceActivationBtn->resize(50,30);
	connect(mMaintenanceActivationBtn,SIGNAL(ButtonToggled(CToggleButtonWidget*)),this,SLOT(ActivationBtnToggled(CToggleButtonWidget*)));

    mWatchdogEnableBtn = new CToggleButtonWidget("./Images/Slider_Green.png","./Images/Slider_Red.png",this);
    mWatchdogEnableBtn->setPos(700,350);
    mWatchdogEnableBtn->resize(50,30);
    connect(mWatchdogEnableBtn,SIGNAL(ButtonToggled(CToggleButtonWidget*)),this,SLOT(WatchdogEnableBtnToggled(CToggleButtonWidget*)));


	Title = new QGraphicsTextItem("Activer mode entretien",this);
	font.setPointSize(16);
	Title->setFont(font);
	Title->setPos(100,60);

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

	mGenerateAlarmBtn = new CTextButtonWidget("Envoyer Alarme",0,30);
	mGenerateAlarmBtn->setParentItem(this);
    mGenerateAlarmBtn->setPos(540,160);
	connect(mGenerateAlarmBtn,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));

    mClearAlarmButton = new CTextButtonWidget("Acquitter Alarme",0,30);
    mClearAlarmButton->setParentItem(this);
    mClearAlarmButton->setPos(540,200);
    mClearAlarmButton->hide();
    connect(mClearAlarmButton,SIGNAL(TxtButtonClicked(CTextButtonWidget*)),this,SLOT(ButtonClicked(CTextButtonWidget*)));

	QGraphicsProxyWidget *Proxy = new QGraphicsProxyWidget(this);
	mAlarmTypeList = new QComboBox();
	Proxy->setWidget(mAlarmTypeList);
    Proxy->setPos(100,190);
	QStringList AlarmTypes;
	AlarmTypes << "Erreur de comptage ZT1"
			   << "Détection Frotteur Négatif"
			   << "Détection Pneu de Guidage"
			   << "Détection Pneu Porteur Intérieur ZT1"
			   << "Détection Pneu Porteur Extérieur ZT1"
			   << "Erreur de comptage ZT2"
			   << "Détection Pneu Porteur Intérieur ZT2"
			   << "Détection Pneu Porteur Extérieur ZT2"
			   << "Panne Équipement ZT1"
			   << "Panne Équipement ZT2";

	mAlarmTypeList->addItems(AlarmTypes);
	mAlarmTypeList->resize(300,30);
	connect(mAlarmTypeList,SIGNAL(currentIndexChanged(int)),this,SLOT(AlarmTypeSelectionChanged(int)));
	Proxy->setZValue(2);
	mAlarmDescription = new QGraphicsTextItem(this);
    mAlarmDescription->setPos(100,160);
	mAlarmDescription->setPlainText("Type d'alarme");


	Proxy = new QGraphicsProxyWidget(this);
	mAlarmRankSpinBox = new QSpinBox();
	Proxy->setWidget(mAlarmRankSpinBox);
    Proxy->setPos(420,190);
	mAlarmRankSpinBox->resize(100,30);
	mRankDescription = new QGraphicsTextItem(this);
    mRankDescription->setPos(420,160);
	mRankDescription->setPlainText("Rang");

	QPen FramePen;
	FramePen.setWidth(3);


    mAlarmsFrame = new QGraphicsRectItem(80,120,650,130,this);
	mAlarmsFrame->setPen(FramePen);

	mFctDescription = new QGraphicsTextItem(this);
	mFctDescription->setPos(200,120);
	mFctDescription->setPlainText("Génération d'alarmes au PCC");
	font.setPointSize(18);
	mFctDescription->setFont(font);

    mWatchdogDisableDescription = new QGraphicsTextItem(this);
    mWatchdogDisableDescription->setPos(694,310);
    mWatchdogDisableDescription->setFont(font);
    mWatchdogDisableDescription->setPlainText("Vigie");

    int yoffset = 30;

	mPPFrame = new QGraphicsRectItem(80,250+yoffset,550,280,this);
	mPPFrame->setPen(FramePen);

	mPPTitle = new QGraphicsTextItem("Activation des pédales pneu porteur",this);
	mPPTitle->setFont(font);
	mPPTitle->setPos(150,250+yoffset);




	font.setPointSize(14);
	mPPIZT1Description = new QGraphicsTextItem("Pédale intérieure ZT1",this);
	mPPIZT1Description->setFont(font);
	mPPIZT1Description->setPos(100,300+15+yoffset);
	mZT1PPIStatus = new CONOFFStatusWidget("");
	mZT1PPIStatus->setParentItem(this);
	mZT1PPIStatus->setPos(320,300+yoffset);

	mPPEZT1Description = new QGraphicsTextItem("Pédale extérieure ZT1",this);
	mPPEZT1Description->setFont(font);
	mPPEZT1Description->setPos(100,350+15+yoffset);
	mZT1PPEStatus = new CONOFFStatusWidget("");
	mZT1PPEStatus->setParentItem(this);
	mZT1PPEStatus->setPos(320,350+yoffset);

	mPPIZT2Description = new QGraphicsTextItem("Pédale intérieure ZT2",this);
	mPPIZT2Description->setFont(font);
	mPPIZT2Description->setPos(100,400+15+yoffset);
	mZT2PPIStatus = new CONOFFStatusWidget("");
	mZT2PPIStatus->setParentItem(this);
	mZT2PPIStatus->setPos(320,400+yoffset);

	mPPEZT2Description = new QGraphicsTextItem("Pédale extérieure ZT2",this);
	mPPEZT2Description->setFont(font);
	mPPEZT2Description->setPos(100,450+15+yoffset);
	mZT2PPEStatus = new CONOFFStatusWidget("");
	mZT2PPEStatus->setParentItem(this);
	mZT2PPEStatus->setPos(320,450+yoffset);

	mMaintenanceModeAutoExitTimer = new QTimer();
	mMaintenanceModeAutoExitTimer->setSingleShot(true);
	connect(mMaintenanceModeAutoExitTimer,SIGNAL(timeout()),this,SLOT(AutoExit()));

    mAlarmRankSpinBox->setValue(1);
    mAlarmRankSpinBox->setMinimum(1);
    mAlarmRankSpinBox->setMaximum(1);
    mRankDescription->setPlainText("N/A");

	HideMaintenanceItems();
}

void CMaintenancePage::resizeEvent(QGraphicsSceneResizeEvent *event)
{
	Q_UNUSED(event)


	mBackgroundRect->setRect(boundingRect());
}

void CMaintenancePage::ButtonClicked(CTextButtonWidget *BtnPtr)
{
    if(BtnPtr == mCancelButton)
	{
		hide();
	}
	else if(BtnPtr == mGenerateAlarmBtn)
	{
		GenerateTK();
	}
    else if(BtnPtr == mClearAlarmButton)
    {
        if(mProgramHandle->ClearMaintenanceCurTKRequest() == RET_OK)
        {
            CZTLog::instance()->AddLogString("[Mode entretien] Acquitement MANUEL d'une TK au PCC.",true);
        }
        else
        {
            mClearAlarmButton->hide();
        }


    }

}

void CMaintenancePage::AlarmTypeSelectionChanged(int index)
{
	switch(index)
	{

		case DETECTION_PG_DETECTION:
		case DETECTION_PPI_DETECTION:
		case DETECTION_PPE_DETECTION:
		case DETECTION_ZT2_PPI_DETECTION:
		case DETECTION_ZT2_PPE_DETECTION:
        {
#ifdef COMPILE_MODBUS_TEST_MODE
			mAlarmRankSpinBox->setValue(1);
            mAlarmRankSpinBox->setMinimum(0);
            mAlarmRankSpinBox->setMaximum(99);
			mRankDescription->setPlainText("Rang");
#else
            mAlarmRankSpinBox->setValue(1);
            mAlarmRankSpinBox->setMinimum(1);
            mAlarmRankSpinBox->setMaximum(36);
            mRankDescription->setPlainText("Rang");
#endif
			break;
		}
		case DETECTION_FN_DETECTION:
		{
#ifdef COMPILE_MODBUS_TEST_MODE
			mAlarmRankSpinBox->setValue(1);
            mAlarmRankSpinBox->setMinimum(0);
            mAlarmRankSpinBox->setMaximum(99);
			mRankDescription->setPlainText("Bogie");
#else
            mAlarmRankSpinBox->setValue(1);
            mAlarmRankSpinBox->setMinimum(1);
            mAlarmRankSpinBox->setMaximum(18);
            mRankDescription->setPlainText("Bogie");
#endif
			break;
		}
		case DETECTION_MAGNETIC_SENSOR_COUNT:
        case DETECTION_ZT2_MAGNETIC_SENSOR_COUNT:
		case DETECTION_PEQ1_DETECTION:
		case DETECTION_PEQ2_DETECTION:
		{
			mAlarmRankSpinBox->setValue(1);
			mAlarmRankSpinBox->setMinimum(1);
			mAlarmRankSpinBox->setMaximum(1);
			mRankDescription->setPlainText("N/A");
			break;
		}
	}
}

void CMaintenancePage::ActivationBtnToggled(CToggleButtonWidget *Btn)
{

	if(Btn->GetButtonState() == TOGGLE_BUTTON_ON)
	{
		if(mProgramHandle->EnterMaintenanceModeRequest() == true)
		{
			ShowMaintenanceItems();
			mMaintenanceModeAutoExitTimer->start(MAINTENANCE_AUTO_EXIT_TIMEOUT);
            CZTLog::instance()->AddLogString("-----------------------------------------------",true);
			CZTLog::instance()->AddLogString("Mode entretien activé:  Zone Tests hors service",true);
		}
		else
		{
			QString str = "Le mode entretien ne peut être activé si:\n- ZT1 ou ZT2 sont activées\n- Un train est sur le CDV d'approche (ZT1 ou ZT2)\n- Des TK sont en cours d'émission\n- La calibration PG est activée";
			QMessageBox::information(0,"Mode Entretien non disponible",str);
			Btn->SetButtonState(TOGGLE_BUTTON_OFF);
		}
	}
	else
	{
		mProgramHandle->ExitMaintenanceModeRequest();
		HideMaintenanceItems();
		mZT1PPEStatus->SetOFF();
		mZT1PPIStatus->SetOFF();
		mZT2PPEStatus->SetOFF();
		mZT2PPIStatus->SetOFF();
		mMaintenanceModeAutoExitTimer->stop();
		CZTLog::instance()->AddLogString("Mode entretien désactivé:  Zone Tests en service.",true);
        CZTLog::instance()->AddLogString("-------------------------------------------------",true);
	}
}

void CMaintenancePage::WatchdogEnableBtnToggled(CToggleButtonWidget *Btn)
{
    if(Btn->GetButtonState() == TOGGLE_BUTTON_ON)
    {
        CZTLog::instance()->AddLogString("[Mode entretien] Vigie réactivée.",true);
        mProgramHandle->SetWatchdogEnabled(true);
    }
    else
    {
        CZTLog::instance()->AddLogString("[Mode entretien] Vigie désactivée.",true);
        mProgramHandle->SetWatchdogEnabled(false);
    }
}

void CMaintenancePage::ShowMaintenanceItems()
{
	mGenerateAlarmBtn->show();
	mAlarmTypeList->show();
	mAlarmRankSpinBox->show();
	mAlarmDescription->show();
	mRankDescription->show();
	mFctDescription->show();

	mPPIZT1Description->show();
	mPPEZT1Description->show();
	mZT1PPEStatus->show();
	mZT1PPIStatus->show();
    if(mProgramHandle->IsZT2PresentInStation())
    {
        mPPIZT2Description->show();
        mPPEZT2Description->show();
        mZT2PPEStatus->show();
        mZT2PPIStatus->show();
    }
	mPPTitle->show();
    mWatchdogDisableDescription->show();

	mAlarmsFrame->show();
	mPPFrame->show();

    mWatchdogEnableBtn->SetButtonState(TOGGLE_BUTTON_ON);
    mWatchdogEnableBtn->show();

    mCancelButton->hide();
}

void CMaintenancePage::HideMaintenanceItems()
{

	mGenerateAlarmBtn->hide();
    mClearAlarmButton->hide();
	mAlarmTypeList->hide();
	mAlarmRankSpinBox->hide();
	mAlarmDescription->hide();
	mRankDescription->hide();
	mFctDescription->hide();

	mPPIZT1Description->hide();
	mPPEZT1Description->hide();
	mPPIZT2Description->hide();
	mPPEZT2Description->hide();
	mZT1PPEStatus->hide();
	mZT1PPIStatus->hide();
	mZT2PPEStatus->hide();
	mZT2PPIStatus->hide();
	mPPTitle->hide();
    mWatchdogDisableDescription->hide();

	mAlarmsFrame->hide();
	mPPFrame->hide();

    mWatchdogEnableBtn->hide();

    mCancelButton->show();

}

void CMaintenancePage::GenerateTK()
{
	int AlarmID = mAlarmTypeList->currentIndex();
	if(AlarmID < 0 || AlarmID >= DETECTION_MAX_DETECTION_ID)
		return;
	int Rank = mAlarmRankSpinBox->value();

	mProgramHandle->SendTKToPCC(AlarmID,Rank);

	CZTLog::instance()->AddLogString(QString().sprintf("[Mode entretien] Émission manuelle d'une alarme au PCC: %s au rang %d",CZTData::GetErrorString(AlarmID),Rank),true);
}

void CMaintenancePage::TKOutputChanged(bool ZT1Active, bool ZT2Active)
{
    if(ZT1Active || ZT2Active)
    {
        mClearAlarmButton->show();
    }
    else
    {
        mClearAlarmButton->hide();
    }
}

void CMaintenancePage::PPActivated(unsigned int PedalID)
{
	switch(PedalID)
	{
		case MAINTENANCE_PPI_ZT1_ID:
		{
			mZT1PPIStatus->SetON();
			CZTLog::instance()->AddLogString("[Mode entretien] Pneu porteur intérieur ZT1 détecté.  TK envoyée au PCC",true);
			break;
		}
		case MAINTENANCE_PPE_ZT1_ID:
		{
			mZT1PPEStatus->SetON();
			CZTLog::instance()->AddLogString("[Mode entretien] Pneu porteur extérieur ZT1 détecté.  TK envoyée au PCC",true);
			break;
		}
		case MAINTENANCE_PPI_ZT2_ID:
		{
			mZT2PPIStatus->SetON();
			CZTLog::instance()->AddLogString("[Mode entretien] Pneu porteur intérieur ZT2 détecté.  TK envoyée au PCC",true);
			break;
		}
		case MAINTENANCE_PPE_ZT2_ID:
		{
			mZT2PPEStatus->SetON();
			CZTLog::instance()->AddLogString("[Mode entretien] Pneu porteur extérieur ZT2 détecté.  TK envoyée au PCC",true);
			break;
		}
	}
}

void CMaintenancePage::AutoExit()
{
	mMaintenanceActivationBtn->SetButtonState(TOGGLE_BUTTON_OFF);
	mProgramHandle->ExitMaintenanceModeRequest();
	HideMaintenanceItems();
	mZT1PPEStatus->SetOFF();
	mZT1PPIStatus->SetOFF();
	mZT2PPEStatus->SetOFF();
	mZT2PPIStatus->SetOFF();
	CZTLog::instance()->AddLogString("Désactivation automatique du mode entretien:  Zone Tests en service.",true);
}

//Grab the mouse if the user clicks outside buttons
void CMaintenancePage::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
	Q_UNUSED(event)
}
void CMaintenancePage::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	Q_UNUSED(event)
}
