// SPDX-License-Identifier: GPL-3.0-or-later

#ifndef V2CTCPDISCOVERY_H
#define V2CTCPDISCOVERY_H

#include <QObject>
#include <QDateTime>
#include <QNetworkAccessManager>
#include <QHash>

#include <network/networkdevicediscovery.h>

/*!
 * \brief Network discovery for V2C Trydan chargers (Modbus TCP).
 *
 * Uses nymea's NetworkDeviceDiscovery to enumerate LAN hosts, then probes
 * each one with \c GET /RealTimeData (the V2C Trydan HTTP REST API) to
 * confirm it is a Trydan.  The probe is HTTP — not Modbus — because the
 * Trydan has no network-accessible Modbus discovery mechanism.
 * cf. AGENTS.md § HTTP and evcc charger/trydan.go.
 *
 * Manual-entry (createMethod "user") bypasses discovery entirely;
 * the plugin calls setupThing() directly with the user-supplied IP.
 */
class V2cTcpDiscovery : public QObject
{
    Q_OBJECT

public:
    struct Result {
        NetworkDeviceInfo networkDeviceInfo;
        QString           ipAddress;
    };

    explicit V2cTcpDiscovery(NetworkDeviceDiscovery *networkDeviceDiscovery,
                             QObject *parent = nullptr);

    void startDiscovery();

    /*! \brief Results available after discoveryFinished() is emitted. */
    QList<Result> results() const;

signals:
    void discoveryFinished();

private:
    void probeAddress(const QHostAddress &address);
    void finishDiscovery();

    NetworkDeviceDiscovery *m_networkDeviceDiscovery = nullptr;
    QNetworkAccessManager   m_nam;

    QDateTime       m_startTime;
    NetworkDeviceInfos m_networkDeviceInfos;
    int             m_pendingProbes   = 0;
    QList<Result>   m_results;
    bool            m_scanFinished    = false;
    bool            m_finished        = false;
};

#endif // V2CTCPDISCOVERY_H
