#include "DataFileTransfer.h"
ZZ_HttpTransfer::ZZ_HttpTransfer(QObject* parent /*= nullptr*/)
{
	m_pNetworkManager = nullptr;
	m_pNetworkManagerThread = nullptr;
	//connect(this, &ZZ_HttpTransfer::SignalInit_Self, this, &ZZ_HttpTransfer::SlotInit_Self);
}

ZZ_HttpTransfer::~ZZ_HttpTransfer()
{
	if (m_pNetworkManager!= nullptr)
	{
		delete m_pNetworkManager;
	}
	if (m_pNetworkManagerThread != nullptr)
	{
		delete m_pNetworkManagerThread;
	}

}

// void ZZ_HttpTransfer::Init_Self()
// {
// 	emit SignalInit_Self();
// }

int ZZ_HttpTransfer::SendData()
{
	return 0;
	if (m_pNetworkManagerThread == nullptr)
	{
		m_pNetworkManagerThread = new QNetworkAccessManager();
		connect(m_pNetworkManagerThread, SIGNAL(finished(QNetworkReply*)), this, SLOT(SlotReplyFinishedThread(QNetworkReply*)));
	}

	QNetworkRequest qnRequest;
	qnRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
	QString qstrURL =  m_qstrUploadURL + "/Data_uper.php";
	qnRequest.setUrl(QUrl(qstrURL));

	QByteArray qbSend;
	QString qstrSend;
	for (int i = 0; i < m_struGrabberRTParams.fscParams.ucDeviceNumber; i++)
	{
		for (int j = 0; j < m_struGrabberRTParams.apsParams.iTotalPosition - 1; j++)
		{

			qstrSend.clear();
			qstrSend = m_vecCalcedData[i][j].qstrGrabDate                                                                + "##";
			qstrSend += /*"FS_SN:"          +*/ QString::fromLocal8Bit(m_struGrabberRTParams.fscParams.strSN[i].c_str()) + "##";
			qstrSend += /*"Position:" +*/       QString("%1").arg(j + 1)                                                 + "##";
			qstrSend += /*"ExpTime:" +*/        QString("%1").arg(m_vecCalcedData[i][j].usExposureTimeInMS)              + "##";
			qstrSend += /*"Bands:" +*/          QString("%1").arg(m_vecCalcedData[i][j].iPixels)                         + "##";
			qstrSend += /*"temp:" +*/           QString("%1").arg(m_vecCalcedData[i][j].fTemperature)                    + "##";
			//send
			qbSend.clear();
			qbSend.append(qstrSend.toLatin1());
			qbSend.append((char*)m_vecCalcedData[i][j].fData, sizeof(float)*m_vecCalcedData[i][j].iPixels);

			m_pNetworkManagerThread->post(qnRequest, qbSend);
			qDebug() << "Network Sending: Data";
 			m_iFlagIsReplied = 0;
 			int iCount = 0;
 			while (!m_iFlagIsReplied)
 			{
 				iCount++;
 				Delay_MSec(500);
 				if (iCount > 20)
 				{
 					m_iFlagIsReplied = 1;
 					qDebug() << "Reply Timeout:Upload Data ";
					qDebug() << "UpLoadAddr:" << qstrURL;
 				}
 			}
		}


	}

	
	
	return 0;
}

int ZZ_HttpTransfer::SendInfo()
{
	return 0;
	if (m_pNetworkManager == nullptr)
	{
		m_pNetworkManager = new QNetworkAccessManager();
		connect(m_pNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(SlotReplyFinished(QNetworkReply*)));
	}

	QNetworkRequest qnRequest;
	qnRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
	QString qstrURL =  m_qstrUploadURL + "/Dev_info_uper.php";
	qnRequest.setUrl(QUrl(qstrURL));
	//qnRequest.setUrl(QUrl("http://172.16.0.234/fileup/Dev_info_uper.php"));

	QByteArray qbSend;
	QString qstrSend;
	QString qstrWaveLength;
	m_iFlagIsReplied = false;
	for (int i = 0; i < m_struGrabberRTParams.fscParams.ucDeviceNumber; i++)
	{
		qstrSend =  "Location:"                      + QString("%1").arg(m_struEC.qstrLocation)                                  + "####";
		qstrSend += "DEV_SN:"                        + QString("%1").arg(m_struEC.qstrDEV_SN)                                    + "####";
		qstrSend += "FS_SN:"                         + QString::fromLocal8Bit(m_struGrabberRTParams.fscParams.strSN[i].c_str())  + "####";
		qstrSend += "GPS_Longtitude:"                + QString("%1").arg(m_struEC.qstrGPS_Longtitude)                            + "####";
		qstrSend += "GPS_Latitude:"                  + QString("%1").arg(m_struEC.qstrGPS_Latitude)                              + "####";
		qstrSend += "GPS_Altitude:"                  + QString("%1").arg(m_struEC.qstrGPS_Altitude)                              + "####";
		qstrSend += "GPS_North:"                     + QString("%1").arg(m_struEC.qstrGPS_North)                                 + "####";
		qstrSend += "InstallationTime:"              + QString("%1").arg(m_struMEC.qstrInstallationTime)                         + "####";
		qstrSend += "NameOfMaintenanceStaff:"        + QString("%1").arg(m_struMEC.qstrNameOfMaintenanceStaff)                   + "####";
		qstrSend += "PhoneNumberOfMaintenanceStaff:" + QString("%1").arg(m_struMEC.qstrPhoneNumberOfMaintenanceStaff)            + "####";
		qstrSend += "Bands:"                         + QString("%1").arg(m_struGrabberRTParams.fscParams.usPixels[i])            + "####";
		qstrSend += "Positions:"                     + QString("%1").arg(m_struGrabberRTParams.apsParams.iTotalPosition-1)       + "####";
		qstrSend += "WaveLength:";

		qDebug() << m_struEC.qstrDEV_SN;

		for (int j=0;j< m_struGrabberRTParams.fscParams.usPixels[i];j++)
		{
			qstrWaveLength = QString("%1").arg(m_struGrabberRTParams.fscParams.fWavelength[i][j]);
			qstrSend += qstrWaveLength;
			if (j == m_struGrabberRTParams.fscParams.usPixels[i]-1)
			{
				//qstrSend += "####";
			}
			else
			{
				qstrSend += ",";
			}
		}

		qbSend = qstrSend.toLatin1();
		m_pNetworkManager->post(qnRequest, qbSend);
		qDebug() << "Network Sending:Dev Info ";
		m_iFlagIsReplied = 0;
		int iCount = 0;
		while (!m_iFlagIsReplied)
		{
			iCount++;
			Delay_MSec(500);
			if (iCount>2)
			{
				m_iFlagIsReplied = 1;
				qDebug() << "Reply Timeout:Upload Info ";
				qDebug() << "UpLoadAddr:" << qstrURL;
			}
		}
	}

	//qDebug() << qstrSend;
	
	return 0;
}

int ZZ_HttpTransfer::SendErr()
{
	return 0;
	if (m_pNetworkManager == nullptr)
	{
		m_pNetworkManager = new QNetworkAccessManager();
		connect(m_pNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(SlotReplyFinished(QNetworkReply*)));
	}

	QNetworkRequest qnRequest;
	qnRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
	QString qstrURL =  m_qstrUploadURL + "/Warning.php";
	qnRequest.setUrl(QUrl(qstrURL));
	//qnRequest.setUrl(QUrl("http://172.16.0.234/fileup/Warning.php"));

	QByteArray qbSend;
	QString qstrSend;
	qbSend.clear();
	qstrSend.clear();

	if (m_struErrInfo.fChassisTempErr==-1000)
	{
	}
	else
	{
		qstrSend += "Case_Temp:" + QString("%1").arg(m_struErrInfo.iDataTransferErr);
	}
	if (m_struErrInfo.fTecTempErr == -1000)
	{
	}
	else
	{
		qstrSend += "##TEC_Temp:" + QString("%1").arg(m_struErrInfo.fTecTempErr);
	}
	if (m_struErrInfo.iDataTransferErr == -1000)
	{
	}
	else
	{
		qstrSend += "##No_Data:" + QString("%1").arg(m_struErrInfo.iDataTransferErr);
	}
	if (m_struErrInfo.iShutterErr == -1000)
	{

	}
	else
	{
		qstrSend += "##Shutter_Pos:" + QString("%1").arg(m_struErrInfo.iDataTransferErr);
	}

	qbSend = qstrSend.toLatin1();
	m_pNetworkManager->post(qnRequest, qbSend);
	qDebug() << "Network Sending:Warning Info ";
	m_iFlagIsReplied = 0;
	int iCount = 0;
	while (!m_iFlagIsReplied)
	{
		iCount++;
		Delay_MSec(500);
		if (iCount > 2)
		{
			m_iFlagIsReplied = 1;
			qDebug() << "Reply Timeout:Upload Info ";
			qDebug() << "UpLoadAddr:" << qstrURL;
		}
	}
	return 0;
}

void ZZ_HttpTransfer::SetErrInfo(ErrInfo struErrInfo)
{
	m_struErrInfo = struErrInfo;
}

void ZZ_HttpTransfer::SetContext(EContext struEC, MEContext struMEC)
{
	m_struEC = struEC;
	m_struMEC = struMEC;

	m_qstrUploadURL = m_struMEC.qstrHTTPServer;
}

void ZZ_HttpTransfer::SetDeviceInfo(RunTimeGrabberParams struGrabberRTParams)
{
	m_struGrabberRTParams = struGrabberRTParams;
}

void ZZ_HttpTransfer::SetCalData(vector<vector<CalDataFrame>> vecCalcedData)
{
	m_vecCalcedData.clear();
	m_vecCalcedData = vecCalcedData;
}

void ZZ_HttpTransfer::Delay_MSec(ZZ_U16 usMS)
{
	QEventLoop qeLoop;
	QTimer::singleShot(usMS, &qeLoop, SLOT(quit()));
	qeLoop.exec();
}

int ZZ_HttpTransfer::SlotReplyFinished(QNetworkReply* qnReply)
{
	
	QString    qstrURL   = qnReply->url().toString();
	QByteArray qbData    = qnReply->readAll();
	if (qnReply->error()== QNetworkReply::NoError)
	{
		qDebug() << "Reply NoError:" << "Server:" << qstrURL;
		m_iFlagIsReplied = 1;
	}
	else
	{
		qDebug() << "Reply Error:" << qnReply->error() << "Server:" << qstrURL;
	}
	qnReply->abort();
	qnReply->close();
	qnReply->deleteLater();
	qnReply = NULL;
	//delete qnReply;
	return 0;
}

int ZZ_HttpTransfer::SlotReplyFinishedThread(QNetworkReply* qnReply)
{

	QString qstrURL = qnReply->url().toString();
	QByteArray qbData = qnReply->readAll();
	if (qnReply->error() == QNetworkReply::NoError)
	{
		qDebug() << "Reply NoError:" << "Server:"<<qstrURL;
		m_iFlagIsReplied = 1;
	}
	else
	{
		qDebug() << "Reply Error:" << qnReply->error()<< "Server:"<<qstrURL;
	}
	qnReply->abort();
	qnReply->close();
	qnReply->deleteLater();
	qnReply = NULL;
	//delete qnReply;
	return 0;
}

// int ZZ_HttpTransfer::SlotInit_Self()
// {
// 	if (m_pNetworkManager == nullptr)
// 	{
// 		m_pNetworkManager = new QNetworkAccessManager();
// 		connect(m_pNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(SlotReplyFinished(QNetworkReply*)));
// 	}
// 	else
// 	{
// 		delete m_pNetworkManager;
// 		m_pNetworkManager = new QNetworkAccessManager();
// 		connect(m_pNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(SlotReplyFinished(QNetworkReply*)));
// 	}
// 	return 0;
// }
