#include "SystemConfigger.h"


 ZZ_SysConfigger::ZZ_SysConfigger(QObject *parent /*= nullptr*/)
 {
#ifdef _DEBUG
	 m_qstrDeviceConfigFilePath =        "E:/WorkSpace/TowerOptoSifAndSpectral/config/DeviceSettings.ini";
	 m_qstrJSONConfigFilePath = "E:/WorkSpace/TowerOptoSifAndSpectral/config/config.json";
#else
	 m_qstrDeviceConfigFilePath = "/home/data/Setting/DeviceSettings.ini";
	 m_qstrJSONConfigFilePath = ("/home/data/Setting/config.json");
#endif // DEBUG

	 m_qsDeviceConfig = NULL;
 }
 
 ZZ_SysConfigger::~ZZ_SysConfigger()
 {
	 if (qfJConfig.isOpen())
	 {
		 qfJConfig.close();
	 }
 }
 
 int ZZ_SysConfigger::Initialize()
 {
	 //////////////////////////////////////////////////////////////////////////load device settings
	 using namespace ZZ_MISCDEF;
	 QMetaEnum enumDeviceModel = QMetaEnum::fromType<ConfiggerDeviceModel>();

	 if (m_qsDeviceConfig!=NULL)
	 {
		delete m_qsDeviceConfig;
	 }
	 m_qsDeviceConfig = new QSettings(m_qstrDeviceConfigFilePath, QSettings::IniFormat);
	 ////FS
	 m_struFSContext.ucDeviceNumber = m_qsDeviceConfig->value(QString("DEVICE INFO/TotalSpectrometer"),-1).toInt();
	 if (m_struFSContext.ucDeviceNumber == -1)
	 {
		 qDebug() << "DEVICE INFO  TotalSpectrometer Value Err.";
		 return 3;
	 }
	 for (ZZ_U8 i=0;i< m_struFSContext.ucDeviceNumber;i++)
	 {
		 QString qstrTemp= m_qsDeviceConfig->value(QString("FS%1/Model").arg(i+1), "Null").toString();
		 m_struFSContext.ucDeviceModel[i]= enumDeviceModel.keysToValue(qstrTemp.toLatin1().data());

		 //int iInterface= m_qsDeviceConfig->value(QString("FS%1/Port").arg(i + 1), -2).toString();
		 //m_struFSContext.strInterface[i] = iInterface;
		 qstrTemp = m_qsDeviceConfig->value(QString("FS%1/Port").arg(i + 1), -2).toString();
		 m_struFSContext.strInterface[i] = qstrTemp.toStdString();

		 qstrTemp = m_qsDeviceConfig->value(QString("FS%1/UID").arg(i + 1), "Null").toString();
		 m_struFSContext.strSN[i] = qstrTemp.toStdString();

		 float fAEMax= m_qsDeviceConfig->value(QString("FS%1/AEMax").arg(i + 1), 0.9).toFloat();
		 m_struFSContext.fMaxFactor[i] = fAEMax;

		 float fAEMin = m_qsDeviceConfig->value(QString("FS%1/AEMin").arg(i + 1), 0.8).toFloat();
		 m_struFSContext.fMinFactor[i] = fAEMin;

		 long lDepth = m_qsDeviceConfig->value(QString("FS%1/Depth").arg(i + 1), 63219).toInt();
		 m_struFSContext.lDepth[i] = lDepth;
	 }

	 ////LS
	 m_struAcqPosition.iTotalPosition = m_qsDeviceConfig->value(QString("LINEAR SHUTTER/TotalPosition"), -1).toInt();
	 if (m_struAcqPosition.iTotalPosition == -1)
	 {
		 qDebug() << "LINEAR SHUTTER  TotalPosition Value Err.";
		 return 4;
	 }

	 for (ZZ_U8 i = 0; i < m_struAcqPosition.iTotalPosition; i++)
	 {
		 int iPosition = m_qsDeviceConfig->value(QString("LINEAR SHUTTER/Position%1").arg(i), -2).toInt();
		 m_struAcqPosition.iPosition[i] = iPosition;
	 }


	 m_struLSContext.usCmdID        = m_qsDeviceConfig->value(QString("LINEAR SHUTTER/DCID")).toInt();
	 m_struLSContext.ucProtocolType = m_qsDeviceConfig->value(QString("LINEAR SHUTTER/Type")).toInt();
	 m_struLSContext.strInterface   = m_qsDeviceConfig->value(QString("LINEAR SHUTTER/Port")).toString().toStdString();

	 //////////////////////////////////////////////////////////////////////////humiture
	 m_struHumitureDeviceInfo.qstrInterfaceName = m_qsDeviceConfig->value(QString("HUMITURE/Port")).toString();
	 //////////////////////////////////////////////////////////////////////////load json settings
	 qfJConfig.setFileName(m_qstrJSONConfigFilePath);
	 bool bRes = qfJConfig.open(QIODevice::ReadOnly);
	 if (!bRes)
	 {
		 qDebug() << "QFile open config file Err.";
		 return 1;
	 }

	 m_qbaJData = qfJConfig.readAll();
	 m_qjdJDoc= QJsonDocument::fromJson(m_qbaJData, &m_qjpeJErr);
	 if (m_qjpeJErr.error != QJsonParseError::NoError)
	 {
		 qDebug() << m_qjpeJErr.errorString();
		 return 2;
	 }
	 m_qjoJObj = m_qjdJDoc.object();
	

	 int iRes = LoadSettingsFromFile_System();
	 if (iRes)
	 {
		 qDebug() << " SysConfigger Initialize Err...LoadSettingsFromFile_System";
		 return iRes;
	 }

	 iRes = LoadSettingsFromFile_MISC();
	 if (iRes)
	 {
		 qDebug() << " SysConfigger Initialize Err...LoadSettingsFromFile_MISC";
		 return iRes;
	 }
	 return 0;
 }

 int ZZ_SysConfigger::GetGrabberRunParams(RunTimeGrabberParams &struGrabberRTParams)
 {
	 struGrabberRTParams.atsParams = m_struAcqTime;
	 struGrabberRTParams.fscParams = m_struFSContext;
	 struGrabberRTParams.lscParam = m_struLSContext;
	 struGrabberRTParams.apsParams = m_struAcqPosition;


 	struGrabberRTParams.issavedark=false;
	// if (m_qjoJObj!= NULL) 判断m_qjoJObj是否有值
 	if (m_qjoJObj.contains("savedark")== true) {
 		QJsonValue savedarkValue = m_qjoJObj.value("savedark");
 		// 判断 QJsonValue 的类型，并提取布尔值
 		if (savedarkValue.isBool()) {
 			struGrabberRTParams.issavedark = savedarkValue.toBool();
 			qDebug() << "Found 'savedark' as boolean. Set issavedark to:" << struGrabberRTParams.issavedark;
 		} else if (savedarkValue.isString()) {
 			// 如果 JSON 中存储的是字符串 "true" 或 "false"
 			QString savedarkStr = savedarkValue.toString();
 			if (savedarkStr.compare("true", Qt::CaseInsensitive) == 0) {
 				struGrabberRTParams.issavedark = true;
 				qDebug() << "Found 'savedark' as string 'true'. Set issavedark to:" << struGrabberRTParams.issavedark;
 			} else if (savedarkStr.compare("false", Qt::CaseInsensitive) == 0) {
 				struGrabberRTParams.issavedark = false;
 				qDebug() << "Found 'savedark' as string 'false'. Set issavedark to:" << struGrabberRTParams.issavedark;
 			} else {
 				qDebug() << "Warning: 'savedark' field has an unexpected string value:" << savedarkStr;
 				// 如果值不是 "true" 或 "false"，可以保持默认值或根据业务逻辑处理
 			}
 		} else {
 			qDebug() << "Warning: 'savedark' field is neither boolean nor string. Value type:" << savedarkValue.type();
 			// 可以选择保持默认值，或者根据需要抛出错误
 		}
 	}else {
 		qDebug()<<"warning no savedark fied";
 	}



	 return 0;
 }

 int ZZ_SysConfigger::GetECParams(EContext &struEC)
 {
	 struEC = m_struEC;
	 return 0;
 }

 int ZZ_SysConfigger::GetMECParams(MEContext &struMEC)
 {
	 struMEC = m_struMEC;
	 return 0;
 }

 int ZZ_SysConfigger::GetMiscParams(HumitureDeviceInfo &struHDI)
{
	 struHDI = m_struHumitureDeviceInfo;
	 return 0;
 }

 int ZZ_SysConfigger::GetParams(RunTimeGrabberParams &struGrabberRTParams, EContext &struEC, MEContext &struMEC, HumitureDeviceInfo &struHDI)
 {
	 GetGrabberRunParams(struGrabberRTParams);
	 GetECParams(struEC);
	 GetMECParams(struMEC);
	 GetMiscParams(struHDI);
	 return 0;
 }

 int ZZ_SysConfigger::LoadSettingsFromFile_IS1()
 {
	 m_struIS1Info.qstrCalFile_U0 = m_qjoJObj.value("IS1UpCalFile").toString();
	 m_struIS1Info.qstrCalFile_D1 = m_qjoJObj.value("IS1DownCalFile1").toString();
	 m_struIS1Info.qstrCalFile_D2 = m_qjoJObj.value("IS1DownCalFile2").toString();
	 m_struIS1Info.qstrCalFile_D3 = m_qjoJObj.value("IS1DownCalFile3").toString();

	
 	return 0;
 }
 
 int ZZ_SysConfigger::LoadSettingsFromFile_iSIF()
 {
	 m_struISIFInfo.qstrCalFile_U0 = m_qjoJObj.value("SIFUpCalFile").toString();
	 m_struISIFInfo.qstrCalFile_D1 = m_qjoJObj.value("SIFDownCalFile1").toString();
	 m_struISIFInfo.qstrCalFile_D2 = m_qjoJObj.value("SIFDownCalFile2").toString();
	 m_struISIFInfo.qstrCalFile_D3 = m_qjoJObj.value("SIFDownCalFile3").toString();
 	 return 0;
 }
 
 int ZZ_SysConfigger::LoadSettingsFromFile_System()
 {
	// QString qstr = m_qjoJObj.value("IntervalTime").toString();
	 m_struAcqTime.qtStartTime=QTime::fromString(m_qjoJObj.value("BeginTime").toString(), "hh:mm");
	 if (!m_struAcqTime.qtStartTime.isValid())
	 {
		 qDebug() << "Invalid BeginTime";
		 return 1;
	 }
	 
#ifdef _DEBUG
	 m_struAcqTime.qtInterval = QTime::fromString(m_qjoJObj.value("IntervalTime").toString(), "ss");
	 if (!m_struAcqTime.qtInterval.isValid())
	 {
		 qDebug() << "Invalid IntervalTime";
		 return 1;
	 }
#else
	 QString qstrTemp;
	 int iTemp = m_qjoJObj.value("IntervalTime").toInt();
	 if (iTemp < 10)
	 {
		 qstrTemp = m_qjoJObj.value("IntervalTime").toString();
		 if (qstrTemp.size() == 1)
		 {
			 qstrTemp = "0" + qstrTemp;
		 }
		 m_struAcqTime.qtInterval = QTime::fromString(qstrTemp, "mm");
	 }
	 else
	 {
		 m_struAcqTime.qtInterval = QTime::fromString(m_qjoJObj.value("IntervalTime").toString(), "mm");
	 }
	 if (!m_struAcqTime.qtInterval.isValid())
	 {
		 qDebug() << "Invalid IntervalTime";
		 return 1;
	 }
#endif

	 m_struAcqTime.qtStopTime = QTime::fromString(m_qjoJObj.value("EndTime").toString(), "hh:mm");
	 if (!m_struAcqTime.qtStopTime.isValid())
	 {
		 qDebug() << "Invalid EndTime";
		 return 1;
	 }

 	return 0;
 }

 int ZZ_SysConfigger::LoadSettingsFromFile_MISC()
 {
	 m_struEC.qstrLocation           = m_qjoJObj.value("Location").toString();
	 m_struEC.qstrGPS_Altitude       = m_qjoJObj.value("GPS_Altitude").toString();
	 m_struEC.qstrGPS_Latitude       = m_qjoJObj.value("GPS_Latitude").toString();
	 m_struEC.qstrGPS_Longtitude     = m_qjoJObj.value("GPS_Longtitude").toString();
	 m_struEC.qstrGPS_North          = m_qjoJObj.value("GPS_North").toString();
	 m_struEC.qstrDEV_SN             = m_qjoJObj.value("Dev_SN").toString();

	 m_struMEC.qstrInstallationTime              = m_qjoJObj.value("InstallationTime").toString();
	 m_struMEC.qstrISIFCalibrationTime           = m_qjoJObj.value("ISIFCalibrationTime").toString();
	 m_struMEC.qstrIS1CalibrationTime            = m_qjoJObj.value("IS1CalibrationTime").toString();
	 m_struMEC.qstrNameOfMaintenanceStaff        = m_qjoJObj.value("NameOfMaintenanceStaff").toString();
	 m_struMEC.qstrPhoneNumberOfMaintenanceStaff = m_qjoJObj.value("PhoneNumberOfMaintenanceStaff").toString();
	 m_struMEC.qstrDownloadUserID                = m_qjoJObj.value("DownloadUserID").toString();
	 m_struMEC.qstrDownlaodAddress               = m_qjoJObj.value("DownlaodAddress").toString();
	 m_struMEC.qstrHTTPServer                    = m_qjoJObj.value("HTTPServer").toString();

	

	 return 0; 
 }

 int ZZ_SysConfigger::LoadSettings_Test()
 {
	 QFile qfTest(m_qstrJSONConfigFilePath);

	 qfTest.open(QFile::ReadOnly);

	 QByteArray qbJData = qfTest.readAll();

	 QJsonParseError jerr;
	 QJsonDocument jdoc(QJsonDocument::fromJson(qbJData, &jerr));
	 if (jerr.error!= QJsonParseError::NoError)
	 {
		 qDebug() << jerr.errorString();
	 }

	 QJsonObject rootobj = jdoc.object();
	 QStringList key = rootobj.keys();
	 QString qtest1 = rootobj.value(rootobj.keys().at(15)).toString();
	 return 0;
 }
