#ifndef UDPDISCOVERYSERVICE_H
#define UDPDISCOVERYSERVICE_H

#include <QObject>
#include <QUdpSocket>
#include <QTimer>
#include <QHostAddress>
#include <QMap>
#include <QString>


#include <QDateTime>

struct NodeInfo {
    QString deviceName;
    QString ipAddress;
    QString versionInfo;
    QString capabilities;
    int ttl = 12;
};

class UdpDiscoveryService : public QObject {
    Q_OBJECT
public:
    explicit UdpDiscoveryService(const QString& deviceName, QObject *parent = nullptr);
    ~UdpDiscoveryService();

    void start();
    void stop();
    void setWatcherMode(bool enabled);
    bool isWatcherMode() const { return m_watcherMode; }
    void sendConnectRequest(const QString& targetIp, bool requestRearCamera = false, bool requestRemoteMic = false);
    void sendSignalingMessage(const QString& targetIp, const QJsonObject& msg);
    void sendReset(const QString& targetIp);

signals:
    void nodesUpdated(const QList<NodeInfo>& nodes);
    void connectRequested(const QString& senderIp, bool requestRearCamera, bool requestRemoteMic);
    void signalingMessageReceived(const QString& senderIp, const QJsonObject& msg);
    void resetRequested(const QString& senderIp);

private slots:
    void readPendingDatagrams();
    void broadcast();

private:
    QString m_deviceName;
    QUdpSocket *m_socketV4;
    QUdpSocket *m_socketV6;
    QTimer *m_broadcastTimer;
    QMap<QString, NodeInfo> m_discoveredNodes;
    QList<QHostAddress> m_localIps;
    bool m_watcherMode = true;

    void updateLocalIps();
    QByteArray createUnifiedPacket(int version, const QJsonObject& payloadMap);
};

#endif // UDPDISCOVERYSERVICE_H
