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

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright (C) 2013 - 2024, nymea GmbH
* Copyright (C) 2024 - 2025, chargebyte austria GmbH
*
* This file is part of nymea-plugins-modbus.
*
* nymea-plugins-modbus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nymea-plugins-modbus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with nymea-plugins-modbus. If not, see <https://www.gnu.org/licenses/>.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "huaweifusionsolardiscovery.h"
#include "extern-plugininfo.h"

HuaweiFusionSolarDiscovery::HuaweiFusionSolarDiscovery(NetworkDeviceDiscovery *networkDeviceDiscovery, quint16 port, const QList<quint16> &slaveIds, QObject *parent)
    : QObject{parent},
      m_networkDeviceDiscovery{networkDeviceDiscovery},
      m_port{port},
      m_slaveIds{slaveIds}
{

}

void HuaweiFusionSolarDiscovery::startDiscovery()
{
    qCInfo(dcHuawei()) << "Discovery: Start searching for Huawei FusionSolar SmartDongle in the network...";
    m_startDateTime = QDateTime::currentDateTime();
    NetworkDeviceDiscoveryReply *discoveryReply = m_networkDeviceDiscovery->discover();
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::hostAddressDiscovered, this, &HuaweiFusionSolarDiscovery::checkNetworkDevice);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, discoveryReply, &NetworkDeviceDiscoveryReply::deleteLater);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [this, discoveryReply](){
        m_networkDeviceInfos = discoveryReply->networkDeviceInfos();

        // Finish with some delay so the last added network device information objects still can be checked.
        QTimer::singleShot(3000, this, [this](){
            qCDebug(dcHuawei()) << "Discovery: Grace period timer triggered.";
            finishDiscovery();
        });
    });
}

QList<HuaweiFusionSolarDiscovery::Result> HuaweiFusionSolarDiscovery::results() const
{
    return m_results;
}

void HuaweiFusionSolarDiscovery::testNextConnection(const QHostAddress &address)
{
    if (!m_pendingConnectionAttempts.contains(address))
        return;

    HuaweiFusionSolar *connection = m_pendingConnectionAttempts[address].dequeue();
    if (m_pendingConnectionAttempts.value(address).isEmpty())
        m_pendingConnectionAttempts.remove(address);

    // Try to connect, maybe it works, maybe not,
    // but retry only once to communicate with the device for reachability check...
    connection->setCheckReachableRetries(1);

    qCDebug(dcHuawei()) << "Discovery: Start searching on" << QString("%1:%2").arg(address.toString()).arg(connection->modbusTcpMaster()->port()) << "slave ID:" << connection->slaveId();
    // Try to connect, maybe it works, maybe not...
    if (!connection->connectDevice()) {
        qCDebug(dcHuawei()) << "Discovery: Failed to connect to" << QString("%1:%2").arg(address.toString()).arg(connection->modbusTcpMaster()->port()) << "slave ID:" << connection->slaveId() << "Continue...";;
        cleanupConnection(connection);
    }
}

void HuaweiFusionSolarDiscovery::checkNetworkDevice(const QHostAddress &address)
{
    QQueue<HuaweiFusionSolar *> connectionQueue;
    foreach (quint16 slaveId, m_slaveIds) {
        HuaweiFusionSolar *connection = new HuaweiFusionSolar(address, m_port, slaveId, this);
        m_connections.append(connection);
        connectionQueue.enqueue(connection);

        connect(connection, &HuaweiFusionSolar::reachableChanged, this, [this, connection](bool reachable){
            if (!reachable) {
                // Disconnected ... done with this connection
                cleanupConnection(connection);
                return;
            }

            // Todo: initialize and check if available
            connect(connection, &HuaweiFusionSolar::initializationFinished, this, [this, connection](bool success){
                Result result;
                result.address = connection->modbusTcpMaster()->hostAddress();
                result.slaveId = connection->slaveId();

                if (success) {
                    qCDebug(dcHuawei()) << "Huawei init finished successfully:" << connection->model() << connection->serialNumber() << connection->productNumber();
                    result.modelName = connection->model();
                    result.serialNumber = connection->serialNumber();
                }

                qCInfo(dcHuawei()) << "Discovery: --> Found" << result.address.toString() << "slave ID:" << result.slaveId;
                m_results.append(result);
            });

            connection->initialize();
        });

        // If we get any error...skip this host...
        connect(connection->modbusTcpMaster(), &ModbusTcpMaster::connectionErrorOccurred, this, [this, connection](QModbusDevice::Error error){
            if (error != QModbusDevice::NoError) {
                qCDebug(dcHuawei()) << "Discovery: Connection error on" << connection->modbusTcpMaster()->hostAddress().toString() << "Continue...";;
                cleanupConnection(connection);
            }
        });

        // If check reachability failed...skip this host...
        connect(connection, &HuaweiFusionSolar::checkReachabilityFailed, this, [this, connection](){
            qCDebug(dcHuawei()) << "Discovery: Check reachability failed on" << connection->modbusTcpMaster()->hostAddress().toString() << "Continue...";;
            cleanupConnection(connection);
        });
    }

    m_pendingConnectionAttempts[address] = connectionQueue;
    testNextConnection(address);
}

void HuaweiFusionSolarDiscovery::cleanupConnection(HuaweiFusionSolar *connection)
{
    if (m_connections.contains(connection)) {
        m_connections.removeAll(connection);
        connection->disconnectDevice();
        connection->deleteLater();
    }

    testNextConnection(connection->modbusTcpMaster()->hostAddress());
}

void HuaweiFusionSolarDiscovery::finishDiscovery()
{
    qint64 durationMilliSeconds = QDateTime::currentMSecsSinceEpoch() - m_startDateTime.toMSecsSinceEpoch();

    // Fill in finished network device information
    for (int i = 0; i < m_results.length(); i++)
        m_results[i].networkDeviceInfo = m_networkDeviceInfos.get(m_results.value(i).address);

    // Cleanup any leftovers...we don't care any more
    foreach (HuaweiFusionSolar *connection, m_connections)
        cleanupConnection(connection);

    qCInfo(dcHuawei()) << "Discovery: Finished the discovery process. Found" << m_results.length()
                       << "inverters in" << QTime::fromMSecsSinceStartOfDay(durationMilliSeconds).toString("mm:ss.zzz");

    emit discoveryFinished();
}
