#include "Scheduler.h"

Scheduler::Scheduler(QObject* parent /*= nullptr*/)
{
	m_iFlagIsOnRestart = 0;
	m_GrabTimer = new QTimer(this);
	connect(m_GrabTimer, &QTimer::timeout, this, &Scheduler::OnTimeCounter);
	connect(this, &Scheduler::SignalSelfStart, this, &Scheduler::StartAsPlanned);
}

Scheduler::~Scheduler()
{
	if (m_GrabTimer != NULL)
	{
		m_GrabTimer->stop();
		delete m_GrabTimer;
	}
}

void Scheduler::SetAcqTimeParams(AcqTimeSettings struAcqTime)
{
	m_struAcqTime = struAcqTime;
}

void Scheduler::Preheating()
{
	qDebug() << "Start Preheating";
#ifdef _DEBUG
	QThread::msleep(5000);
#else
	QThread::msleep(900000);//NEED TO CHANGE BEFOR HAND TO CUSTOM
#endif
	qDebug() << "Preheating Finished";
}

void Scheduler::SelfStart()
{
	emit SignalSelfStart();
}

void Scheduler::StartAsPlanned()
{
	bool bStopWait = false;
	
	while (!bStopWait)
	{
		QThread::msleep(10000);
		QTime qtTime = QTime::currentTime();
		if (m_struAcqTime.qtStartTime <= qtTime && qtTime < m_struAcqTime.qtStopTime)
		{
			bStopWait = true;
		}
	}

 	int iIntervalInMS = m_struAcqTime.qtInterval.hour() * 3600 * 1000 + m_struAcqTime.qtInterval.minute() * 60 * 1000 + m_struAcqTime.qtInterval.second() * 1000;

	m_GrabTimer->start(iIntervalInMS);

	QThread::msleep(5000);
	qDebug() << "it's time to start work.";
	emit SignalGrabOnce();
	//this->OnTimeCounter();
	//emit &QTimer::timeout;
}

int Scheduler::OnTimeCounter()
{
	QTime qtTime = QTime::currentTime();
	if (m_struAcqTime.qtStartTime <= qtTime && qtTime < m_struAcqTime.qtStopTime)
	{
		if (m_iFlagIsOnRestart)
		{

		}

		qDebug() << "it's time to work...work work.";
		emit SignalGrabOnce();
		return 0;
	}
	else
	{
		if (!m_iFlagIsOnRestart)
		{
			m_iFlagIsOnRestart = 1;
		}
		emit SignalZeroHoldCurrent();
		system("gpio write 1 0");//�豸�ϵ�
		qDebug() << "gpio write 1 0......"<<endl;
		qDebug() << "Non working time. Idling......";
		return 0;
	}
}
