#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonObject>
#include <QByteArray>
#include <QImage>
#include <QDebug>

class HyperionMock : public QObject
{
    Q_OBJECT
public:
    HyperionMock(quint16 port, QObject *parent = nullptr) : QObject(parent)
    {
        _server = new QTcpServer(this);
        connect(_server, &QTcpServer::newConnection, this, &HyperionMock::handleConnection);
        if (!_server->listen(QHostAddress::Any, port)) {
            qCritical() << "Failed to start mock server:" << _server->errorString();
        } else {
            qDebug() << "Mock server listening on port" << port;
        }
    }

private slots:
    void handleConnection()
    {
        QTcpSocket *socket = _server->nextPendingConnection();
        connect(socket, &QTcpSocket::readyRead, this, [socket]() {
            QByteArray data = socket->readAll();
            QJsonDocument doc = QJsonDocument::fromJson(data);
            if (doc.isObject()) {
                QJsonObject obj = doc.object();
                if (obj.contains("command") && obj["command"].toString() == "image") {
                    if (obj.contains("imagedata")) {
                        QByteArray imageData = QByteArray::fromBase64(obj["imagedata"].toString().toUtf8());
                        QImage image;
                        image.loadFromData(imageData, "PNG");
                        if (!image.isNull()) {
                            QString filename = QString("received_frame_%1.png").arg(QDateTime::currentMSecsSinceEpoch());
                            image.save(filename);
                            qDebug() << "Received and saved image:" << filename;
                        } else {
                            qWarning() << "Failed to decode image data.";
                        }
                    }
                }
            }
        });
    }

private:
    QTcpServer *_server;
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    HyperionMock mock(19444);
    return app.exec();
}

#include "hyperion-mock.moc"
