#include "BD357Ctrl.h"
#include "MainGrabber.h"
#include "lwgps.h"
#include "lwrb.h"
#include "time.h"
BD357Controller::BD357Controller(QObject* parent /*= nullptr*/)
{
	m_iFlagIsGPSValid = 0;
	m_iFlagIsContinuousUpdating = 0;
	m_pSerialPort = NULL;

	//connect(m_pSerialPort, &QSerialPort::readyRead, this, &BD357Controller::HandleReadyRead);
	connect(this, &BD357Controller::Signal_InitSelf, this, &BD357Controller::Slot_InitSelf);
	//connect(m_pMainGrabber,&CMainGrabber::Signal_InitFinished,this, &BD357Controller::Slot_SyncDateOnce);
}



BD357Controller::~BD357Controller()
{
	if (m_pSerialPort != NULL)
	{
		m_pSerialPort->close();
		delete m_pSerialPort;
	}
}

int BD357Controller::SetContext(CMainGrabber& pMainGrabber)
{
	m_pMainGrabber = &pMainGrabber;
	return 0;
}

int BD357Controller::SetupMessagePipeline()
{
	connect(m_pMainGrabber, &CMainGrabber::Signal_InitFinished, this, &BD357Controller::Slot_SyncDateOnce);
	return 0;
}

int BD357Controller::SyncDateOnce()
{
	using namespace ZZ_MISCDEF;

	//bool    bFlagFinish = 1;
	bool    bFlagFinish = false;
	size_t  uiCount      = 0;
	//ZZ_U8 u8Rx,u8Tx;


	while (!bFlagFinish)
	{
		m_qbReadData.clear();

		while (m_qbReadData.size()< 1000)
		{
			m_pSerialPort->waitForReadyRead(1000);
			m_qbReadData.append(m_pSerialPort->readAll());
			qDebug() << "waiting for gps data..." << m_qbReadData.size();
		}

		qDebug() << m_qbReadData.size() << endl;

		lwgps_process(&m_hLWGPS, m_qbReadData, m_qbReadData.size());
		
		m_qbReadData.clear();


		if (uiCount<2)
		{
			uiCount++;
			continue;
		}
		else
		{
			/*if (m_hLWGPS.is_valid)
			{
				bFlagFinish = 1;
			}*/
		}
		//need to disable 
		//qDebug() << "one status :"<< m_hLWGPS.is_valid << m_hLWGPS .sats_in_use<< m_hLWGPS .year<<"-" << m_hLWGPS .month<<"-" << m_hLWGPS.date << "-" << m_hLWGPS.hours << ":" << m_hLWGPS.minutes << ":" << m_hLWGPS.seconds << ":" << endl;
		int iRes = ZZ_FormatTime(m_hLWGPS.year, m_hLWGPS.month, m_hLWGPS.date, m_hLWGPS.hours, m_hLWGPS.minutes, m_hLWGPS.seconds);
		if (iRes != 0)
		{
			continue;
		}
		else
		{
			bFlagFinish = 1;
			time_t stdtime = m_qdtDateTime.toTime_t();
			time_t stdtimeUTC = m_qdtDateTimeUTC.toTime_t();
			
#ifdef WIN32

#else
			stime(&stdtimeUTC);
#endif
			

			system("gpio write 4 1");
			qDebug() << "system(gpio write 4 1)";
			// 
			//m_qdtDateTime.currentMSecsSinceEpoch
			 //m_qdtDateTime.currentMSecsSinceEpoch();
		}
		//bFlagFinish = 1;
	}
	qDebug() << "Signal_StartCapture emitted.";
	emit Signal_StartCapture();

	return 0;
}

int BD357Controller::StartContinuousUpdating()
{
	m_iFlagIsContinuousUpdating = 1;

	while (m_iFlagIsContinuousUpdating)
	{
		m_qbReadData.clear();

		while (m_qbReadData.size() < 1000)
		{
			m_pSerialPort->waitForReadyRead(1000);
			m_qbReadData.append(m_pSerialPort->readAll());
		}
		//qDebug() << m_qbReadData.size() << endl;

		lwgps_process(&m_hLWGPS, m_qbReadData, m_qbReadData.size());

		if (m_hLWGPS.is_valid&&(!m_iFlagIsGPSValid))
		{
			emit Signal_UpdateStatus(1);
		}

		if ((!m_hLWGPS.is_valid)&& m_iFlagIsGPSValid)
		{
			emit Signal_UpdateStatus(0);
		}
		m_qbReadData.clear();
	}
	return 0;
}

int BD357Controller::Initialize(GPSInfo &struGPSI)
{
	m_struGPSInfo = struGPSI;
	emit Signal_InitSelf();

	return 0;
}



int BD357Controller::VSlot_SkipSyncDateOnce()
{
	emit Signal_StartCapture();
	qDebug() << "Signal_StartCapture";
	return 0;
}

int BD357Controller::ZZ_FormatTime(ZZ_U8 u8Year, ZZ_U8 u8Month, ZZ_U8 u8Day, ZZ_U8 u8Hour, ZZ_U8 u8Minute, ZZ_U8 u8Second)
{
	int iYear = u8Year + 2000;

	QDateTime qdtTestDate(QDate(iYear, u8Month, u8Day), QTime(u8Hour, u8Minute, u8Second));

	if (qdtTestDate.isValid())
	{
		qDebug() << qdtTestDate;
		m_qdtDateTime    = qdtTestDate;
		m_qdtDateTimeUTC = qdtTestDate;
		//UTC+0 to UTC+8
		m_qdtDateTime.addSecs(3600 * 8);
		return 0;
	}
	else
	{
		return -1;
	}

	return -2;
	//bool b1 = startDate.isValid();
	//QString end = startDate.toString("yyyy.MM.dd hh:mm:ss");
	//qDebug() << end;
	//QString qstrSyncDate = QString("%1-%2-%3-%4-%5-%6").arg(iYear,    4, 10, QLatin1Char('0')).arg(u8Month,  2, 10, QLatin1Char('0'))
	//	                                               .arg(u8Day,    2, 10, QLatin1Char('0')).arg(u8Hour,   2, 10, QLatin1Char('0'))
	//	                                               .arg(u8Minute, 2, 10, QLatin1Char('0')).arg(u8Second, 2, 10, QLatin1Char('0'));
	//	
	//m_qdtDateTime.fromString(qstrSyncDate, "yyyy-MM-dd-hh-mm-ss");
	//qDebug() << qstrSyncDate;
	//bool b = m_qdtDateTime.isValid();
	//QString begin = m_qdtDateTime.toString("yyyy.MM.dd hh:mm:ss");
	//qDebug() << begin;
	/*qstrSyncDate = "20" + QString::number(m_hLWGPS.year) + "-"
		+ QString::number(m_hLWGPS.month) + "-"
		+ QString::number(m_hLWGPS.date) + "-"
		+ QString::number(m_hLWGPS.hours) + "-"
		+ QString::number(m_hLWGPS.minutes) + "-"
		+ QString::number(m_hLWGPS.seconds);
	qdtSync.fromString(qstrSyncDate, "yyyy-MM-dd-hh-mm-ss");
	qDebug() << qstrSyncDate;
	bool b = qdtSync.isValid();
	QString begin = qdtSync.toString("yyyy.MM.dd hh:mm:ss");
	std::string strtime = begin.toStdString();
	qDebug() << begin;*/
}

int BD357Controller::Slot_InitSelf()
{
	m_qbReadData.clear();

	//QString qstrPortName = struGPSI.qstrInterfaceName;

	if (m_pSerialPort != NULL)
	{
		m_pSerialPort->close();
		delete m_pSerialPort;
	}

	m_pSerialPort = new QSerialPort;

	m_pSerialPort->setPortName(m_struGPSInfo.qstrInterfaceName);
	//m_pSerialPort->setReadBufferSize(512);  in this project 0 seems a better param.
	bool bRes = m_pSerialPort->setBaudRate(m_struGPSInfo.iBaud);
	if (!bRes)
	{
		//qDebug() << "Err:setBaudRate Failed.Exit Code:1";
		printf("Err:setBaudRate Failed.Exit Code:1");
		//std::cout << "Err.setBaudRate Failed" << std::endl;
		return 1;
	}

	bRes = m_pSerialPort->open(QIODevice::ReadWrite);
	if (!bRes)
	{
		//qDebug() << "Err:open Failed.Exit Code:2";
		printf("Err:open Failed.Exit Code:2");
		//std::cout << "Err.open Failed" << std::endl;
		return 2;
	}

	/////
	lwgps_init(&m_hLWGPS);

	lwrb_init(&m_hlwrbBuffer, m_u8GPSDataBuffer, sizeof(m_u8GPSDataBuffer));

	return 0;
}

int BD357Controller::Slot_SyncDateOnce()
{
	//emit Signal_StartCapture();
	SyncDateOnce();
	return 0;
}

// 
// int BD357Controller::HandleReadyRead()
// {
// 	size_t uiSize = 0;
// 	m_qbReadData.append(m_pSerialPort->readAll());
// 	if (m_qbReadData.size()<2048)
// 	{
// 		lwrb_write(&m_hlwrbBuffer, &m_qbReadData, m_qbReadData.size());
// 		m_qbReadData.clear();
// 	}
// 	else
// 	{
// 		m_qbReadData.clear();
// 	}
// 
// 	return 0;
// }
