#include "network.h"
#include "logger.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>

Network::Network(QObject *parent)
    : QObject{parent}
{
    bool ok = m_udpSocket.bind(QHostAddress::AnyIPv4, 18000);

    if (!ok) {
        LOG_ERROR("udp bind failed: {}", m_udpSocket.errorString().toUtf8().data());
        return;
    }

    connect(&m_udpSocket, &QUdpSocket::readyRead, this, &Network::onUdpReadyRead);
}

Network::~Network()
{

}

void Network::onUdpReadyRead()
{
    QByteArray datagram;
    QHostAddress addr;
    quint16 port;
    QJsonDocument doc;
    QJsonParseError jsonError;
    while (m_udpSocket.hasPendingDatagrams()) 
    {
        datagram.resize(int(m_udpSocket.pendingDatagramSize()));
        m_udpSocket.readDatagram(datagram.data(), datagram.size(), &addr, &port);

        LOG_DEBUG("receive from {}:{}", addr.toString().toUtf8().data(), port);

        doc = QJsonDocument::fromJson(datagram, &jsonError);
        if(jsonError.error == QJsonParseError::NoError && doc.isObject())
        {
            LOG_INFO("{}", doc.toJson().data());
            emit updateScreen(doc.object());
        }
    }
}