#include "threadReceive.h"
#include "cigarette.h"
#include "basecamera.h"
void threadReceive::start_work()
{
	//start(HighestPriority);
	start();
}

void threadReceive::stop()
{
	isLoop = false;
	BOOL  bDontLinger = FALSE;
	mSocket->abort();
	filemSocket->abort();
	// wait();
}

void threadReceive::init(std::string IP,int port)
{
	ip = QString::fromStdString(IP);

	mSocket = new QUdpSocket(this);
	mSocket->bind(port + NumberOfSupportedCameras*2+1, QUdpSocket::ShareAddress);
	connect(mSocket, &QUdpSocket::readyRead, this, &threadReceive::processPendingDatagram);

	filemSocket = new QUdpSocket(this);
	filemSocket->bind(port + NumberOfSupportedCameras*2+2, QUdpSocket::ShareAddress);
	connect(filemSocket, &QUdpSocket::readyRead, this, &threadReceive::fileprocessPendingDatagram);
}

void threadReceive::processPendingDatagram()
{
	// 拥有等待的数据报
	while (mSocket->hasPendingDatagrams())
	{
		QByteArray datagram;

		// 让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
		datagram.resize(mSocket->pendingDatagramSize());

		// 接收数据报，将其存放到datagram中
		mSocket->readDatagram(datagram.data(), datagram.size());
		QString data = datagram;

		emit sendMsgToCigratte(data);
	}
}

void threadReceive::fileprocessPendingDatagram()
{
	QString filename;
	std::fstream file;
	// 拥有等待的数据报
	while (filemSocket->hasPendingDatagrams())
	{
		QByteArray datagram;
		// 让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
		datagram.resize(filemSocket->pendingDatagramSize());

		// 接收数据报，将其存放到datagram中
		filemSocket->readDatagram(datagram.data(), datagram.size());
		QString data = datagram;

		QString str = data.mid(0, 4);
		if (str == "SYNC")
		{
			str = data.mid(4, 3);
			if (str == "str")
			{
				filename = data.mid(7, data.length() - 7);
				file.open(("../conf/" + filename.toStdString()).c_str(), std::ios::out | std::ios::trunc | ios::binary);
			}
			else if (str == "con")
			{
				str = data.mid(7, data.length() - 7);
				if (file.is_open())
				{
					file.write(str.toStdString().c_str(), str.toStdString().size());
				}
			}
			else if (str == "end")
			{
				str = data.mid(7, data.length() - 7);
				file.close();
			}
		}
	}
}