/*******************************************************************************
*                                                                              *
* Société de Transports de Montréal.                                    	   *
* 2012                                                                         *
*                                                                              *
* Projet Zones Tests                                                           *
*                                                                              *
*                                                                              *
*                                                                              *
*******************************************************************************/
/*
    Description:
    Classe de gestion de la configuration.  Gère l'assignation et l'accès aux
    paramètres contenues dans le fichier de configuration de la ZT.
    Cette classe est Singleton.
    
*/

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

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

#include "ZTconfigmgr.h"

CZTConfigMgr CZTConfigMgr::mSingleton;

CZTConfigMgr::CZTConfigMgr()
{

    //Initialize default variable values.

    //External IO Modules
    mConfig_ExtIO_MasterIPAddr = "192.168.0.1";
    mConfig_ExtIOModulesConfigList.clear();

    //DataQ  Module
    mDataQIPAddr.clear();

    //Station config
    mConfig_Station_StationName = "UNKNOWN";
//    mConfig_Station_LaserSensorCalib = 0;

    //This is the value of verbosity.  Returns -1 if log is disabled
    mEngLogVerbosity = -1;

	//Lazer probes
	mConfig_LazerProbeModulesConfigList.clear();

	//Simulator activation
	mUseSimulator = false;

    //Modbus communication with CC
    mUseModbusCCMode = ZT_CONFIG_MODBUS_ENABLE_AUTODETECT;
    mModbusCCIFName = "INVALID";

    //SAMBA drive parameters
    mActivateSAMBADrive = false;
    mSAMBADomain.clear();

    //SFTP server parameters
    mActivateSFTPClient = false;

    //PI historian parameters
    mEnablePIHistorian = false;
    mPIHistorianModbusPort = 503;
    mPIHistorianModbusDevID = 1;
}

ZTConfigResult CZTConfigMgr::LoadZTConfig()
{
    mZTConfigFile = new QFile("./Configuration/ZT.cfg");
    if (!mZTConfigFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        delete mZTConfigFile;
        return ZT_CONFIG_FILE_ERROR;
    }

    bool finished = false;
    QString string;
    QString temp;
    int pos;
    while(!finished)
    {

        string.clear();
        string = mZTConfigFile->readLine(1024);
        if(string.isEmpty())
        {
            finished = true;
            break;
        }

		if(string.at(0) != '#' && string.at(0) != '\n')
		{
			string.remove("\n");    //remove trailing "\n" characters inserted by QFile.readline
			string.remove(' ');     //remove spaces
			pos = string.indexOf('=');
			if(pos != -1)
			{
				pos += 1;


				//External modules configuration parameters
				if(string.contains("EXTIO_MASTER_IP"))
				{
					mConfig_ExtIO_MasterIPAddr = string.mid(pos);
					CEngLog::instance()->AddLogString(QString().sprintf("EXTIO_MASTER_IP = %s",mConfig_ExtIO_MasterIPAddr.toUtf8().constData()));
				}
                else if(string.contains("DATAQ_IP"))
                {
                    mDataQIPAddr = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString().sprintf("DATAQ_IP = %s",mDataQIPAddr.toUtf8().constData()));
                }
				else if(string.contains("EXTIO_430_MOD_PHYS_ADDR"))
				{
					stExtModulesConfig_t ModuleConfig;
					ModuleConfig.ModuleID = atoi(string.mid(pos-2,1).toUtf8().constData());
					ModuleConfig.ModuleSlaveAddress = atoi(string.mid(pos).toUtf8().constData());
					ModuleConfig.ModuleType = EXT_IO_TYPE_430;
					mConfig_ExtIOModulesConfigList.append(ModuleConfig);
					CEngLog::instance()->AddLogString(QString().sprintf("EXTIO_430_MOD_PHYS_ADDR = %d",ModuleConfig.ModuleSlaveAddress));
				}
				else if(string.contains("EXTIO_440_MOD_PHYS_ADDR"))
				{
					stExtModulesConfig_t ModuleConfig;
					ModuleConfig.ModuleID = atoi(string.mid(pos-2,1).toUtf8().constData());
					ModuleConfig.ModuleSlaveAddress = atoi(string.mid(pos).toUtf8().constData());
					ModuleConfig.ModuleType = EXT_IO_TYPE_440;
                    mConfig_ExtIOModulesConfigList.append(ModuleConfig);
					CEngLog::instance()->AddLogString(QString().sprintf("EXTIO_440_MOD_PHYS_ADDR = %d",ModuleConfig.ModuleSlaveAddress));
                }
                else if(string.contains("EXTIO_470_MOD_PHYS_ADDR"))
                {
                    stExtModulesConfig_t ModuleConfig;
                    ModuleConfig.ModuleID = atoi(string.mid(pos-2,1).toUtf8().constData());
                    ModuleConfig.ModuleSlaveAddress = atoi(string.mid(pos).toUtf8().constData());
                    ModuleConfig.ModuleType = EXT_IO_TYPE_470;
                    mConfig_ExtIOModulesConfigList.append(ModuleConfig);
					CEngLog::instance()->AddLogString(QString().sprintf("EXTIO_470_MOD_PHYS_ADDR = %d",ModuleConfig.ModuleSlaveAddress));
                }
				else if(string.contains("SIMULATEUR"))
				{
					if(string.mid(pos) == "OUI")
						mUseSimulator = true;
                    else if(string.mid(pos) == "NON")
						mUseSimulator = false;
					else
						CEngLog::instance()->AddLogString(QString().sprintf("Invalid SIMULATOR parameter: %s",string.mid(pos).toUtf8().constData()));

					CEngLog::instance()->AddLogString(QString().sprintf("SIMULATEUR = %d",mUseSimulator));
				}
                else if(string.contains("ENGLOG"))
                {
                    mEngLogVerbosity = atoi(string.mid(pos).toUtf8().constData());
                    if(mEngLogVerbosity < 0 || mEngLogVerbosity > 3)
                    {
						CEngLog::instance()->AddLogString(QString().sprintf("Invalid Eng Log verbosity: %d.  Eng Log disabled",mEngLogVerbosity));
                        mEngLogVerbosity = -1;
                    }
                    else
						CEngLog::instance()->AddLogString(QString().sprintf("Eng Log verbosity = %d",mEngLogVerbosity));
                }
                else if(string.contains("UTILISER_MODBUS_CC"))
                {
                    if(string.mid(pos) == "OUI")
                    {
                        mUseModbusCCMode = ZT_CONFIG_MODBUS_ENABLE_FORCE_ON;
                        CEngLog::instance()->AddLogString(QString().sprintf("Comm. Modbus avec la CC activée (forcée)"),1);
                    }
                    else if(string.mid(pos) == "NON")
                    {
                        mUseModbusCCMode = ZT_CONFIG_MODBUS_ENABLE_FORCE_OFF;
                        CEngLog::instance()->AddLogString(QString().sprintf("Comm. Modbus avec la CC désactivée (forcée)"),1);
                    }
                    else if(string.mid(pos) == "AUTO")
                    {
                        mUseModbusCCMode = ZT_CONFIG_MODBUS_ENABLE_AUTODETECT;
                        CEngLog::instance()->AddLogString(QString().sprintf("Comm. Modbus avec la CC = détection automatique"),1);
                    }
                    else
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_CC parameter: %s",string.mid(pos).toUtf8().constData()));
                }
                else if(string.contains("MODBUS_CC_DEVID"))
                {
                    bool OK;
                    mModbusCCDevID = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_CC_DEVID parameter: %s",string.mid(pos).toUtf8().constData()));
                        mModbusCCDevID = 1;
                    }
                    else
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Device ID Modbus CC = %d",mModbusCCDevID));
                    }
                }
                else if(string.contains("MODBUS_CC_PORT"))
                {
                    bool OK;
                    mModbusCCPort = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_CC_PORT parameter: %s",string.mid(pos).toUtf8().constData()));
                        mModbusCCPort = 6060;
                    }
                    CEngLog::instance()->AddLogString(QString().sprintf("Port Modbus CC = %d",mModbusCCPort));
                }
                else if(string.contains("MODBUS_CC_ETH_IF"))
                {
                    mModbusCCIFName = (string.mid(pos));
                    CEngLog::instance()->AddLogString(QString("Interface Modbus CC = %1").arg(mModbusCCIFName),1);
                }
                else if(string.contains("MODBUS_SEI_DEVID"))
                {
                    bool OK;
                    mModbusSEIDevID = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_SEI_DEVID parameter: %s",string.mid(pos).toUtf8().constData()));
                        mModbusSEIDevID = 0;
                    }
                    CEngLog::instance()->AddLogString(QString().sprintf("Modbus DevID SEI = %d",mModbusSEIDevID));
                }
                else if(string.contains("MODBUS_SEI_PORT"))
                {
                     bool OK;
                    mModbusSEIPort = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_SEI_PORT parameter: %s",string.mid(pos).toUtf8().constData()));
                        mModbusSEIPort = 6060;
                    }
                    CEngLog::instance()->AddLogString(QString().sprintf("Port Modbus SEI = %d",mModbusSEIPort));
                }

                //Station configuration parameters
                else if(string.contains("STATION"))
                {
                    mConfig_Station_StationName = string.mid(pos);
					CEngLog::instance()->AddLogString(QString().sprintf("STATION = %s",mConfig_Station_StationName.toUtf8().constData()));
                }
//                else if(string.contains("CALIB_PNEU_GUIDAGE"))
//                {
//                    mConfig_Station_LaserSensorCalib = atoi(string.mid(pos).toUtf8().constData());
//                    qDebug("CALIB_PNEU_GUIDAGE = %d",mConfig_Station_LaserSensorCalib);
//                }

				//Lazer probes serial port configuration parameters
				else if(string.contains("SONDE_LASER_INT"))
				{
					stLazerProbesConfig_t LazerProbeConfig;
					LazerProbeConfig.ProbeType = LAZER_PROBE_TYPE_INTERNAL;
					LazerProbeConfig.ProbeID = atoi(string.mid(pos-2,1).toUtf8().constData());
					LazerProbeConfig.SerialPort = string.mid(pos);
					mConfig_LazerProbeModulesConfigList.append(LazerProbeConfig);
					CEngLog::instance()->AddLogString(QString().sprintf("LazerProbeINT_%d = Port: %s",LazerProbeConfig.ProbeID,LazerProbeConfig.SerialPort.toUtf8().constData()));
				}
				else if(string.contains("SONDE_LASER_EXT"))
				{
					stLazerProbesConfig_t LazerProbeConfig;
					LazerProbeConfig.ProbeType = LAZER_PROBE_TYPE_EXTERNAL;
					LazerProbeConfig.ProbeID = atoi(string.mid(pos-2,1).toUtf8().constData());
					LazerProbeConfig.SerialPort = string.mid(pos);
					mConfig_LazerProbeModulesConfigList.append(LazerProbeConfig);
					CEngLog::instance()->AddLogString(QString().sprintf("LazerProbeEXT_%d = Port: %s",LazerProbeConfig.ProbeID,LazerProbeConfig.SerialPort.toUtf8().constData()));
				}
                else if(string.contains("ACTIVER_SAMBA"))
                {
                    if(string.mid(pos) == "OUI")
                    {
                        mActivateSAMBADrive = true;
                        CEngLog::instance()->AddLogString(QString().sprintf("Copie sur répertoire SAMBA activée"),1);
                    }
                    else
                    {
                        mActivateSAMBADrive = false;
                        CEngLog::instance()->AddLogString(QString().sprintf("Copie sur répertoire SAMBA désactivée"),1);
                    }
                }
                else if(string.contains("NETWORK_SHARE_PATH"))
                {
                    mSAMBAMountPoint = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Point d'accès SAMBA: %1").arg(mSAMBAMountPoint),1);
                }
                else if(string.contains("NETWORK_SHARE_LOGIN"))
                {
                    mSAMBALogin = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Login SAMBA: %1").arg(mSAMBALogin),1);
                }
                else if(string.contains("NETWORK_SHARE_PASSWORD"))
                {
                    mSAMBAPassword = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Password SAMBA: %1").arg(mSAMBAPassword),1);
                }
                else if(string.contains("NETWORK_SHARE_DOMAIN"))
                {
                    mSAMBADomain = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Domaine SAMBA: %1").arg(mSAMBADomain),1);
                }
                else if(string.contains("ACTIVER_SFTP"))
                {
                    if(string.mid(pos) == "OUI")
                    {
                        mActivateSFTPClient = true;
                        CEngLog::instance()->AddLogString(QString().sprintf("Copie sur serveur SFTP activée"),1);
                    }
                    else
                    {
                        mActivateSFTPClient = false;
                        CEngLog::instance()->AddLogString(QString().sprintf("Copie sur serveur SFTP désactivée"),1);
                    }
                }
                else if(string.contains("SFTP_LOGIN"))
                {
                    mSFTPLogin = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Login SFTP: %1").arg(mSFTPLogin),1);
                }
                else if(string.contains("SFTP_PASSWORD"))
                {
                    mSFTPPassword = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Mot de passe SFTP: %1").arg(mSFTPPassword),1);
                }
                else if(string.contains("SFTP_SERVER_ADDRESS"))
                {
                    mSFTPAddress = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Adresse du serveur SFTP: %1").arg(mSFTPAddress),1);
                }
                else if(string.contains("SFTP_DESTINATION"))
                {
                    mSFTPRemoteDir = string.mid(pos);
                    CEngLog::instance()->AddLogString(QString("Répertoire distant SFTP %1").arg(mSFTPRemoteDir),1);
                }
                else if(string.contains("ACTIVER_HISTORIEN_PI"))
                {
                    if(string.mid(pos) == "OUI")
                    {
                        mEnablePIHistorian = true;
                        CEngLog::instance()->AddLogString(QString().sprintf("Historien PI activé"),1);
                    }
                    else
                    {
                        mEnablePIHistorian = false;
                        CEngLog::instance()->AddLogString(QString().sprintf("Historien PI activé"),1);
                    }
                }
                else if(string.contains("HISTORIEN_PI_DEVID"))
                {
                    bool OK;
                    mPIHistorianModbusDevID = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid HISTORIEN_PI_DEVID parameter: %s",string.mid(pos).toUtf8().constData()));
                        mPIHistorianModbusDevID = 1;
                    }
                    CEngLog::instance()->AddLogString(QString().sprintf("Historien PI DevID = %d",mPIHistorianModbusDevID));
                }
                else if(string.contains("HISTORIEN_PI_PORT"))
                {
                     bool OK;
                    mPIHistorianModbusPort = (string.mid(pos).toInt(&OK));
                    if(OK == false)
                    {
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid HISTORIEN_PI_PORT parameter: %s",string.mid(pos).toUtf8().constData()));
                        mPIHistorianModbusPort = 503;
                    }
                    CEngLog::instance()->AddLogString(QString().sprintf("Port Modbus Historien PI = %d",mPIHistorianModbusPort));
                }


             }
        }
    }


    mZTConfigFile->close();
    delete mZTConfigFile;

    return ZT_CONFIG_OK;
}

QString CZTConfigMgr::GetStationName()
{
    return mConfig_Station_StationName;
}

QString CZTConfigMgr::GetExtIOIPAddress()
{
    return mConfig_ExtIO_MasterIPAddr;
}

QList<stExtModulesConfig_t> * CZTConfigMgr::GetExtIOModulesConfigList()
{
    return &mConfig_ExtIOModulesConfigList;
}

QList<stLazerProbesConfig_t> * CZTConfigMgr::GetLazerProbesConfigList()
{
	return &mConfig_LazerProbeModulesConfigList;
}

int CZTConfigMgr::GetEngLog()
{
    return mEngLogVerbosity;
}

bool CZTConfigMgr::GetSimulatorEnabled()
{
	return mUseSimulator;
}

ZTConfigModbusEnableMode CZTConfigMgr::GetModbusCCEnabled()
{
    return mUseModbusCCMode;
}
int CZTConfigMgr::GetModbusCCDevID()
{
    return mModbusCCDevID;
}

QString CZTConfigMgr::GetModbusCCIFName()
{
    return mModbusCCIFName;
}

int CZTConfigMgr::GetModbusCCPort()
{
    return mModbusCCPort;
}

int CZTConfigMgr::GetModbusSEIPort()
{
    return mModbusSEIPort;
}

int CZTConfigMgr::GetModbusSEIDevID()
{
    return mModbusSEIDevID;
}

QString CZTConfigMgr::GetDataQIPAddress()
{
    return mDataQIPAddr;
}

bool CZTConfigMgr::GetSAMBADriveActivated()
{
    return mActivateSAMBADrive;
}

QString CZTConfigMgr::GetSAMBAMountPoint()
{
    return mSAMBAMountPoint;
}

QString CZTConfigMgr::GetSAMBALogin()
{
    return mSAMBALogin;
}

QString CZTConfigMgr::GetSAMBAPassword()
{
    return mSAMBAPassword;
}

QString CZTConfigMgr::GetSAMBADomain()
{
    return mSAMBADomain;
}

bool CZTConfigMgr::GetSFTPActivated()
{
    return mActivateSFTPClient;
}

QString CZTConfigMgr::GetSFTPLogin()
{
    return mSFTPLogin;
}

QString CZTConfigMgr::GetSFTPPassword()
{
    return mSFTPPassword;
}

QString CZTConfigMgr::GetSFTPServerAddress()
{
    return mSFTPAddress;
}

QString CZTConfigMgr::GetSFTPServerRemoteDir()
{
    return mSFTPRemoteDir;
}

bool CZTConfigMgr::GetPIHistorianEnabled()
{
    return mEnablePIHistorian;
}

int CZTConfigMgr::GetPIHistorianModbusDevID()
{
    return mPIHistorianModbusDevID;
}

int CZTConfigMgr::GetPIHistorianModbusPort()
{
    return mPIHistorianModbusPort;
}
