#include "cudpreciever.h"
#include <QHostAddress>
#include <QDebug>
cUdpObject::cUdpObject(QObject *parent)
	:QObject (parent)
{

}
cUdpObject::~cUdpObject()
{
	unbind();
}

void cUdpObject::bind(int port)
{
	bool need_bind = false;
	if (!m_pSock)
		need_bind = true;
	else if (m_nPort!=port)
	{
		unbind();
		need_bind = true;
	}

	if (need_bind)
	{
		m_pSock = new QUdpSocket(this);
		if (m_pSock->bind(QHostAddress::Any,port))
		{
			m_nPort  = port;
			connect(m_pSock,&QUdpSocket::readyRead,this,&cUdpObject::readData);
		}
		else {
			m_pSock->deleteLater();
			m_pSock = nullptr;
		}
	}
}
void cUdpObject::unbind()
{
	if (m_pSock)
	{
		m_pSock->close();
		m_pSock->deleteLater();
		m_pSock = nullptr;
	}
}
void cUdpObject::quit()
{
	unbind();
	QThread * t = QThread::currentThread();
	if (t)
		t->quit();
}

void cUdpObject::readData()
{
	static char bufrev[65536];
	if (m_pSock)
	{
		while (m_pSock->hasPendingDatagrams())
		{
			qint64 rev = m_pSock->readDatagram(bufrev,65536);
			if (rev)
				emit newSig(QByteArray(bufrev,rev));
		}
	}
}

cUdpReciever::cUdpReciever(QObject * pa)
	: QObject(pa)
{
	m_pUdpObj = new cUdpObject;
	m_pWThread = new QThread(this);
	connect(this, &cUdpReciever::cmd_start,m_pUdpObj,&cUdpObject::bind,Qt::QueuedConnection);
	connect(this, &cUdpReciever::cmd_stop,m_pUdpObj,&cUdpObject::unbind,Qt::QueuedConnection);
	connect(this, &cUdpReciever::cmd_quit,m_pUdpObj,&cUdpObject::quit,Qt::QueuedConnection);
	connect(m_pUdpObj, &cUdpObject::newSig,this,&cUdpReciever::newSig,Qt::QueuedConnection);
	m_pUdpObj->moveToThread(m_pWThread);
	m_pWThread->start();

}
cUdpReciever::~cUdpReciever()
{
	qDebug()<<"cUdpReciever::~cUdpReciever()";
	if (m_pUdpObj)
	{
		emit cmd_quit();
		m_pUdpObj->deleteLater();
		m_pUdpObj = nullptr;
	}
	m_pWThread->wait();
	qDebug()<<"cUdpReciever::~cUdpReciever() Finished";
}
bool cUdpReciever::isRunning()
{
	return m_pUdpObj->isRunning();
}
void cUdpReciever::startListen(int nport)
{
	emit cmd_start(nport);

}
void cUdpReciever::stopRecv()
{
	emit cmd_stop();
}
