/*******************************************************************************
*                                                                              *
* 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
    mUseModbusCC = false;
}

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")
                        mUseModbusCC = true;
                    else if(string.mid(pos) == "NON")
                        mUseSimulator = false;
                    else
                        CEngLog::instance()->AddLogString(QString().sprintf("Invalid MODBUS_CC parameter: %s",string.mid(pos).toUtf8().constData()));

                    CEngLog::instance()->AddLogString(QString().sprintf("Comm. Modbus avec la CC = %d",mUseModbusCC));
                }
                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));
                }

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


            }
        }
    }


    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;
}

bool CZTConfigMgr::GetModbusCCEnabled()
{
    return mUseModbusCC;
}
int CZTConfigMgr::GetModbusCCDevID()
{
    return mModbusCCDevID;
}

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

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