#include "MainDataGrabber.h"

CMainDataGrabber::CMainDataGrabber(QObject* parent /*= nullptr*/)
{
	m_piFlagCaptureThreadStatus_Signal = NULL;
	m_piFlagCaptureThreadStatus_Dark = NULL;

	//m_GrabTimer = new QTimer(this);

	m_iFlagIsCapturing = false;
	m_iFlagIsCapturing_Signal = false;
	m_iFlagIsCapturing_Dark = false;

	//qRegisterMetaType<DataFrame>("DataFrame");
	//qRegisterMetaType<vector<vector<DataFrame>>>();
}

CMainDataGrabber::~CMainDataGrabber()
{
	if (m_pControlThread.size() != 0)
	{
		for (int i=0;i< m_pControlThread.size();i++)
		{
			delete m_pControlThread[i];
		}
	}
	m_pControlThread.clear();

	if (m_piFlagCaptureThreadStatus_Signal!=NULL)
	{
		delete m_piFlagCaptureThreadStatus_Signal;
	}

	if (m_piFlagCaptureThreadStatus_Dark != NULL)
	{
		delete m_piFlagCaptureThreadStatus_Dark;
	}


// 	if (m_GrabTimer!=NULL)
// 	{
// 		m_GrabTimer->stop();
// 		delete m_GrabTimer;
// 	}
}

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

void CMainDataGrabber::SubDataFrame(DataFrame& dfLeft, DataFrame const dfRight, int iCount)
{
	for (int i = 0; i < iCount; i++)
	{
		dfLeft.lData[i] = dfLeft.lData[i]- dfRight.lData[i];
	}
}

int CMainDataGrabber::SetContext(RunTimeGrabberParams struGrabberRTParams, DataFileProcessor &dfpSaver, Scheduler &sScheduler)
{
	SetGrabberParams(struGrabberRTParams);
	SetGrabberFileProcessor(dfpSaver);
	SetTimer(sScheduler);
	return 0;
}

int CMainDataGrabber::SetContext(RunTimeGrabberParams struGrabberRTParams, DataFileProcessor &dfpSaver, Scheduler &sScheduler, CMainDataUploader &mduUploader)
{

	SetGrabberParams(struGrabberRTParams);
	SetGrabberFileProcessor(dfpSaver);
	SetTimer(sScheduler);
	SetUploader(mduUploader/*, struGrabberRTParams*/);
	return 0;
}

void CMainDataGrabber::Init_Normal()
{
	InitThreadStatus();
	InitializeWorkers();
	StartWorkers();
	SetupMsgPipelines();
}

int CMainDataGrabber::SetGrabberParams(RunTimeGrabberParams struGrabberRTParams)
{
	m_struAcqTime = struGrabberRTParams.atsParams;
	m_struDeviceContext = struGrabberRTParams.fscParams;
	m_struAcqPosSetting = struGrabberRTParams.apsParams;
	m_struLinearShutterContext = struGrabberRTParams.lscParam;

	m_iTotalThreads = m_struDeviceContext.ucDeviceNumber;

	m_struRTGP = struGrabberRTParams;
	return 0;
}

int CMainDataGrabber::SetGrabberFileProcessor(DataFileProcessor &dfpSaver)
{
	m_pdfpSaver = &dfpSaver;
	return 0;
}

int CMainDataGrabber::SetTimer(Scheduler &sScheduler)
{
	m_psScheduler = &sScheduler;
	return 0;
}

int CMainDataGrabber::SetUploader(CMainDataUploader &mduUploader/*, RunTimeGrabberParams struGrabberRTParams*/)
{
	m_pmduUploader = &mduUploader;
	return 0;
}

int CMainDataGrabber::InitLS()
{
 	//InitializeWorkers();
 	//SetupMsgPipelines_RunTime();
 	//StartWorkers();
	
	if (m_struLinearShutterContext.strInterface=="GPIO")
	{
		qDebug() << "Debugging GPIO Init Started";

		m_vecDSS.clear();

		if (m_struLinearShutterContext.ucProtocolType == 100)
		{
			DSStatus DSSOne;

			QString qstrChannel = QString::number(m_struLinearShutterContext.usCmdID, 10);
			if (qstrChannel.size() != 2)
			{
				qDebug() << "Dual Shutter Channel Parse Err.";
				return -1;
			}
			else
			{
				DSSOne.strChannelA = qstrChannel.toStdString()[0];
				DSSOne.strChannelB = qstrChannel.toStdString()[1];
				DSSOne.iChannelA = 1;
				DSSOne.iChannelB = 1;
			}

			m_vecDSS.push_back(DSSOne);
			
			
		}
	}
	else
	{ 
		PortInfo piTemp;
		piTemp.qstrFullPortName = QString::fromStdString(m_struLinearShutterContext.strInterface);
		m_ctrlLS.ILMES_InitializeComm(piTemp, m_struLinearShutterContext.ucProtocolType, m_struLinearShutterContext.usCmdID);
		ControllerParams cpTemp;
		bool res = m_ctrlLS.ILMES_InitializeParams(cpTemp);
		m_ctrlLS.ILMES_SetPosition(m_struAcqPosSetting.iPosition, m_struAcqPosSetting.iTotalPosition);
	}
	

	//m_ctrlLS.ILMES_MoveToPos(2);
	return 0;
}

int CMainDataGrabber::InitThreadStatus()
{
	if (m_piFlagCaptureThreadStatus_Signal!=NULL)
	{
		delete m_piFlagCaptureThreadStatus_Signal;
	}
	m_piFlagCaptureThreadStatus_Signal = new int[m_iTotalThreads];
	for (int i = 0; i < m_iTotalThreads; i++)
	{
		m_piFlagCaptureThreadStatus_Signal[i] = 0;
	}


	if (m_piFlagCaptureThreadStatus_Dark != NULL)
	{
		delete m_piFlagCaptureThreadStatus_Dark;
	}
	m_piFlagCaptureThreadStatus_Dark = new int[m_iTotalThreads];
	for (int i = 0; i < m_iTotalThreads; i++)
	{
		m_piFlagCaptureThreadStatus_Dark[i] = 0;
	}
	return 0;
}

int CMainDataGrabber::ResetThreadStatus()
{
	for (int i = 0; i < m_iTotalThreads; i++)
	{
		m_piFlagCaptureThreadStatus_Signal[i] = 0;
		m_piFlagCaptureThreadStatus_Dark[i] = 0;
	}
	return 0;
}

int CMainDataGrabber::InitializeWorkers()
{
	for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	{
		m_piFlagCaptureThreadStatus_Signal[i] = 0;
		m_piFlagCaptureThreadStatus_Dark[i] = 0;

		FSInfo fsInfo;
		fsInfo.strInterface = m_struDeviceContext.strInterface[i];
		fsInfo.ucDeviceModel = m_struDeviceContext.ucDeviceModel[i];
		fsInfo.strSN = m_struDeviceContext.strSN[i];
		fsInfo.fMaxFactor = m_struDeviceContext.fMaxFactor[i];
		fsInfo.fMinFactor = m_struDeviceContext.fMinFactor[i];
		fsInfo.lDepth = m_struDeviceContext.lDepth[i];

		CAbstractFSController* m_pWorkThread = new CAbstractFSController;
		m_pWorkThread->SetRunParas(i, fsInfo);
// 		m_pWorkThread->InitializeFSControl();
// 
// 		DeviceAttribute daAttrTemp;
// 		m_pWorkThread->GetDeviceAttr(daAttrTemp);
// 		m_struDeviceContext.usPixels[i] = (ZZ_U16)daAttrTemp.iPixels;
// 		for (ZZ_U16 j = 0; j < daAttrTemp.iPixels; j++)
// 		{
// 			m_struDeviceContext.fWavelength[i][j] = daAttrTemp.fWaveLengthInNM[j];
// 		}
 		m_pControlThread.push_back(m_pWorkThread);
	}
// 	m_struRTGP.fscParams = m_struDeviceContext;
// 	m_pdfpSaver->SetDeviceInfo(m_struDeviceContext);
// 	m_pmduUploader->SetRTGP(m_struRTGP);
	return 0;
}

int CMainDataGrabber::StartWorkers()
{

	for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	{
		QThread *pWorkThreadHolder = new QThread();
		m_pControlThread[i]->moveToThread(pWorkThreadHolder);
		pWorkThreadHolder->start();

		m_pControlThread[i]->InitializeFSControl_Self();
		/// <summary>
		while (!m_pControlThread[i]->iFlagInit)
		{
			Delay_MSec(1000);
		}
		/// </summary>
		/// <returns></returns>
		DeviceAttribute daAttrTemp;
		m_pControlThread[i]->GetDeviceAttr(daAttrTemp);
		m_struDeviceContext.usPixels[i] = (ZZ_U16)daAttrTemp.iPixels;
		for (ZZ_U16 j = 0; j < daAttrTemp.iPixels; j++)
		{
			m_struDeviceContext.fWavelength[i][j] = daAttrTemp.fWaveLengthInNM[j];
		}
	}

	m_struRTGP.fscParams = m_struDeviceContext;
	m_pdfpSaver->SetDeviceInfo(m_struDeviceContext);
	m_pmduUploader->SetRTGP(m_struRTGP);
	
	return 0;
}

int CMainDataGrabber::SetupMsgPipelines()
{
	//connect(this, &CMainDataGrabber::SignalStartGrabOnce, this, &CMainDataGrabber::StartGrab);
	//connect(m_GrabTimer, &QTimer::timeout, this, &CMainDataGrabber::OnTimeCounter);
	//FS
	for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	{
		connect(this, &CMainDataGrabber::SignalStartGrabOnce_Signal, m_pControlThread[i], &CAbstractFSController::StartAcquisitionSignal);
		connect(this, &CMainDataGrabber::SignalStartGrabOnce_Dark, m_pControlThread[i], &CAbstractFSController::StartAcquisitionDark);
		connect(m_pControlThread[i], &CAbstractFSController::SignalAcqFinished_Signal, this, &CMainDataGrabber::HandleThreadEvent_Signal);
		connect(m_pControlThread[i], &CAbstractFSController::SignalAcqFinished_Dark, this, &CMainDataGrabber::HandleThreadEvent_Dark);
	}

	connect(this, &CMainDataGrabber::SignalGrabOnceFinished, this, &CMainDataGrabber::GrabOnceFinished);
	connect(m_psScheduler, &Scheduler::SignalGrabOnce, this, &CMainDataGrabber::OnTimeCounter);
	connect(m_psScheduler, &Scheduler::SignalZeroHoldCurrent, this, &CMainDataGrabber::OnZeroHoldCurrent);
	connect(this, &CMainDataGrabber::SignalStartGrab, this, &CMainDataGrabber::StartGrabTimer);
	connect(this, &CMainDataGrabber::SignalGrabOnceFinished_Signal, this, &CMainDataGrabber::GrabOnceFinished_Signal);
	connect(this, &CMainDataGrabber::SignalGrabOnceFinished_Dark, this, &CMainDataGrabber::GrabOnceFinished_Dark);

	//net work
	connect(this, &CMainDataGrabber::SignalPushOneDataFrame, m_pmduUploader,&CMainDataUploader::SlotPushOneDataFrame);

	//shutter
	connect(this,&CMainDataGrabber::SignalLSInit,this,&CMainDataGrabber::InitLS);
	
	return 0;
}

int CMainDataGrabber::SetupMsgPipelines_RunTime()
{
	for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	{
		connect(this, &CMainDataGrabber::SignalStartGrabOnce_Signal, m_pControlThread[i], &CAbstractFSController::StartAcquisitionSignal);
		connect(this, &CMainDataGrabber::SignalStartGrabOnce_Dark, m_pControlThread[i], &CAbstractFSController::StartAcquisitionDark);
		connect(m_pControlThread[i], &CAbstractFSController::SignalAcqFinished_Signal, this, &CMainDataGrabber::HandleThreadEvent_Signal);
		connect(m_pControlThread[i], &CAbstractFSController::SignalAcqFinished_Dark, this, &CMainDataGrabber::HandleThreadEvent_Dark);
	}
	return 0;
}

int CMainDataGrabber::StartGrab()
{
	emit SignalStartGrab();
	return 0;
}

void CMainDataGrabber::Init_Self()
{
	emit SignalLSInit();
	return;
}

int CMainDataGrabber::HandleThreadEvent_Signal(int iThreadID, int iFlagStatus)
{
	m_piFlagCaptureThreadStatus_Signal[iThreadID] = iFlagStatus;

	bool bFinished = true;
	for (int i = 0; i < m_iTotalThreads; i++)
	{
		if (m_piFlagCaptureThreadStatus_Signal[i] != 1)
		{
			bFinished = false;
			break;
		}
	}

	if (bFinished)
	{
		emit SignalGrabOnceFinished_Signal();
	}
	return 0;
}

int CMainDataGrabber::HandleThreadEvent_Dark(int iThreadID, int iFlagStatus)
{
	m_piFlagCaptureThreadStatus_Dark[iThreadID] = iFlagStatus;

	bool bFinished = true;
	for (int i = 0; i < m_iTotalThreads; i++)
	{
		if (m_piFlagCaptureThreadStatus_Dark[i] != 1)
		{
			bFinished = false;
			break;
		}
	}

	if (bFinished)
	{
		emit SignalGrabOnceFinished_Dark();
	}
	return 0;
}

int CMainDataGrabber::GrabOnceFinished_Signal()
{
	m_iFlagIsCapturing_Signal = false;
	return 0;
}

int CMainDataGrabber::GrabOnceFinished_Dark()
{
	m_iFlagIsCapturing_Dark = false;
	return 0;
}

//int CMainDataGrabber::InitLS_Self(/*RunTimeGrabberParams struGrabberRTParams, DataFileProcessor &dfpSaver, Scheduler &sScheduler*/)
//{
//	//SetGrabberFileProcessor(dfpSaver);
//	//SetGrabberParams(struGrabberRTParams);
//	//SetTimer(sScheduler);
//	InitLS();
//	return 0;
//}

int CMainDataGrabber::StartGrabTimer()
{
	//////////////////////////////////////////////////////////////////////////start
	////check start time
// 	bool bStopWait = false;
// 	while (!bStopWait)
// 	{
// 		QTime qtTime = QTime::currentTime();
// 		if (m_struAcqTime.qtStartTime >= qtTime && qtTime<m_struAcqTime.qtStopTime)
// 		{
// 			bStopWait = true;
// 		}
// 	}
 	//start
 	//int iIntervalInMS =m_struAcqTime.qtInterval.hour()*3600*1000+ m_struAcqTime.qtInterval.minute()*60*1000+ m_struAcqTime.qtInterval.second()*1000;
 	//m_GrabTimer->start(3000);
	//////////////////////////////////////////////////////////////////////////test
// 	m_iFlagIsCapturing = true;
// 	emit SignalStartGrabOnce();
//  	while (m_iFlagIsCapturing)
//  	{
//  		QThread::msleep(1000);
//  	}
// 	
// 	m_iFlagIsCapturing = true;
// 	InitThreadStatus();
// 	emit SignalStartGrabOnce();
// 	while (m_iFlagIsCapturing)
// 	{
// 		QThread::msleep(1000);
// 	}
// 	qDebug() << "Allgrab stopped" << " Thread ID:" <<2;
	////final test code eat my ass
// 	m_iFlagIsCapturing = 1;
// 	
// 	
// 	for (int i=0;i<5;i++)
// 	{
// 		m_iFlagIsCapturing_Signal = 1;
// 		emit SignalStartGrabOnce_Signal();
// 		while (m_iFlagIsCapturing_Signal)
// 		{
// 			Delay_MSec(200);
// 			qDebug() << "msleep" << 200;
// 		}
// 		
// 		m_iFlagIsCapturing_Dark = 1;
// 		emit SignalStartGrabOnce_Dark();
// 		while (m_iFlagIsCapturing_Dark)
// 		{
// 			Delay_MSec(200);
// 			qDebug() << "msleep" << 200;
// 		}
// 		
// 	}
// 	qDebug() << "for quit";
// 	
	return 0;
}

int CMainDataGrabber::GrabOnceFinished()
{
	m_iFlagIsCapturing = false;
// 	QTimer t;
// 	t.start();
// 	while (1)
// 	{
// 		QThread::msleep(1);
// 		QCoreApplication::processEvents();
// 	}
	return 0;
}

 int CMainDataGrabber::OnTimeCounter()
 {
	 bool bRes;
	 QString qstrCMD_A,qstrCMD_B,qstrCMD_Temp;

	 if (m_iFlagIsCapturing)
	 {
		 qDebug() << "Fatal Warning.Last capture not finished.New acquisition will not start";
		 return 1000;
	 }
	 m_iFlagIsCapturing = 1;

	 //return 0;
	// m_struAcqPosSetting.iTotalPosition = 5;

	 //m_pdfpSaver->WriteDataFile();
	 for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	 {
		 m_pControlThread[i]->ClearBuffer();
	 }



	 if (m_struLinearShutterContext.strInterface == "GPIO")
	 {
	 }
	 else
	 {
		 ////hold current
		 bRes = m_ctrlLS.SetHoldCurrent(0.4f);
		 if (!bRes)
		 {
			 qDebug() << "SetHoldCurrent 0.4 Failed";
		 }
		 Delay_MSec(1000);
		 ////
	 }
	
	 for (int i=0;i< m_struAcqPosSetting.iTotalPosition-1;i++)
	 {
		 ResetThreadStatus();

		 ////move to start
		 if (m_struLinearShutterContext.strInterface == "GPIO")
		 {
			 if (m_struLinearShutterContext.ucProtocolType == 100)
			 {
				if (i==0)
				{
					qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelA);
					qstrCMD_A = "gpio write " + qstrCMD_Temp + " 1";

					qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelB);
					qstrCMD_B = "gpio write " + qstrCMD_Temp + " 0";

					system(qstrCMD_A.toLatin1());
					system(qstrCMD_B.toLatin1());

					qDebug() << qstrCMD_A;
					qDebug() << qstrCMD_B;

					Delay_MSec(500);
				}
				if (i==1)
				{
					qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelA);
					qstrCMD_A = "gpio write " + qstrCMD_Temp + " 0";

					qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelB);
					qstrCMD_B = "gpio write " + qstrCMD_Temp + " 1";

					system(qstrCMD_A.toLatin1());
					system(qstrCMD_B.toLatin1());

					qDebug() << qstrCMD_A;
					qDebug() << qstrCMD_B;

					Delay_MSec(500);
				}
				

			 }
		 }
		 else
		 {
			 qDebug() << "Start ILMES_MoveToPos:" << i + 1;
			 if (i == 0)
			 {
				 m_ctrlLS.ILMES_MoveToPos(i + 1);
			 }
			 else
			 {
				 m_ctrlLS.MoveTo(m_struAcqPosSetting.iPosition[1]);
			 }
			 m_ctrlLS.ILMES_MoveToPos(i + 1);
			 qDebug() << "Stop ILMES_MoveToPos:" << i + 1;
		 }
		 ////move to end

		
		// m_struAcqPosSetting.iPosition[i + 1];
		 m_iFlagIsCapturing_Signal = 1;
		 emit SignalStartGrabOnce_Signal();
		 while (m_iFlagIsCapturing_Signal)
		 {
			 Delay_MSec(1000);
		 }


		 ////move to
		 if (m_struLinearShutterContext.strInterface == "GPIO")
		 {
			 if (m_struLinearShutterContext.ucProtocolType == 100)
			 {
				 qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelA);
				 qstrCMD_A = "gpio write " + qstrCMD_Temp + " 0";

				 qstrCMD_Temp = QString::fromStdString(m_vecDSS[0].strChannelB);
				 qstrCMD_B = "gpio write " + qstrCMD_Temp + " 0";

				 system(qstrCMD_A.toLatin1());
				 system(qstrCMD_B.toLatin1());

				 qDebug() << qstrCMD_A;
				 qDebug() << qstrCMD_B;
			 }
		 }
		 else
		 {
			 qDebug() << "Start ILMES_MoveToPos:" << 0;
			 m_ctrlLS.ILMES_MoveToPos(0);
			 qDebug() << "Stop ILMES_MoveToPos:" << 0;
		 }

		 //m_struAcqPosSetting.iPosition[0];
		 m_iFlagIsCapturing_Dark = 1;
		 emit SignalStartGrabOnce_Dark();
		 while (m_iFlagIsCapturing_Dark)
		 {
			 Delay_MSec(1000);
		 }
	 }

	 if (m_struLinearShutterContext.strInterface == "GPIO")
	 {
	 }
	 else
	 {
		 ////hold current
		 bRes = m_ctrlLS.SetHoldCurrent(0);
		 if (!bRes)
		 {
			 qDebug() << "SetHoldCurrent 0 Failed";
		 }
		 Delay_MSec(1000);
		 ////
	 }

	 std::vector<std::vector<DataFrame>> vecData;
	
	 for (ZZ_U8 i = 0; i < m_struDeviceContext.ucDeviceNumber; i++)
	 {
		 std::vector<DataFrame> vecDark, vecSignal, vecResult;
		 m_pControlThread[i]->GetBuffer(vecDark, vecSignal);
		 for (size_t j=0;j< vecDark.size();j++)
		 {
			 SubDataFrame(vecSignal[j], vecDark[j], m_struDeviceContext.usPixels[i]);
		 }
		 vecData.push_back(vecSignal);
		 qDebug() << "ucDeviceNumber" << i << "  Data Size" << vecSignal.size();
		 //vecData[i].push_back();
	 }
	
	 //emit SignalPushOneDataFrame(vecData);
	 m_pmduUploader->SetData(vecData);
	 emit SignalPushOneDataFrame();
	 m_pdfpSaver->SetData(vecData);
	 m_pdfpSaver->WriteDataFile();
	 m_iFlagIsCapturing = 0;

// 	 qDebug() << "-------------------------------------------busy" << QTime::currentTime().toString();
// 	 QThread::msleep(5000);
// 	 return 0;	 
//  	if (m_iFlagIsCapturing)
//  	{
//  		
//  	}
// 	m_iFlagIsCapturing = 1;
	//qDebug() << "-------------------------------------------return";
	//return 1;
// 	for (int i = 0; i < 5; i++)
// 	{
// 		m_iFlagIsCapturing_Signal = 1;
// 		emit SignalStartGrabOnce_Signal();
// 		while (m_iFlagIsCapturing_Signal)
// 		{
// 			//Delay_MSec(1000);
// 			QThread::msleep(100);
// 			QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
// 			//qDebug() << "msleep" << 1000;
// 		}
// 
// 		m_iFlagIsCapturing_Dark = 1;
// 		emit SignalStartGrabOnce_Dark();
// 		while (m_iFlagIsCapturing_Dark)
// 		{
// 			Delay_MSec(1000);
// 			QThread::msleep(100);
// 			QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
// 			//qDebug() << "msleep" << 1000;
// 		}
// 
// 	}
// 	qDebug() << "for quit";
// 
//  	
//  	emit SignalGrabOnceFinished();
 	return 0;
 }

 int CMainDataGrabber::OnZeroHoldCurrent()
 {
	bool bRes = m_ctrlLS.SetHoldCurrent(0);
	if (!bRes)
	{
		qDebug() << "OnZeroHoldCurrent Failed";
	}

	 return 0;
 }

