// 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 "smamodbusbatteryinverterdiscovery.h"
#include "extern-plugininfo.h"

#include "sma.h"

SmaModbusBatteryInverterDiscovery::SmaModbusBatteryInverterDiscovery(NetworkDeviceDiscovery *networkDeviceDiscovery, quint16 port, quint16 modbusAddress, QObject *parent):
    QObject(parent),
    m_networkDeviceDiscovery{networkDeviceDiscovery},
    m_port(port),
    m_modbusAddress(modbusAddress)
{
    m_gracePeriodTimer.setSingleShot(true);
    m_gracePeriodTimer.setInterval(3000);
    connect(&m_gracePeriodTimer, &QTimer::timeout, this, [this](){
        qCDebug(dcSma()) << "Discovery: Grace period timer triggered.";
        finishDiscovery();
    });
}

void SmaModbusBatteryInverterDiscovery::startDiscovery()
{
    qCInfo(dcSma()) << "Discovery: Searching for SMA battery inverters in the network...";
    NetworkDeviceDiscoveryReply *discoveryReply = m_networkDeviceDiscovery->discover();
    m_startDateTime = QDateTime::currentDateTime();

    connect(discoveryReply, &NetworkDeviceDiscoveryReply::hostAddressDiscovered, this, &SmaModbusBatteryInverterDiscovery::checkNetworkDevice);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, discoveryReply, &NetworkDeviceDiscoveryReply::deleteLater);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
        qCDebug(dcSma()) << "Discovery: Network discovery finished. Found" << discoveryReply->networkDeviceInfos().length() << "network devices";
        m_networkDeviceInfos = discoveryReply->networkDeviceInfos();
        m_gracePeriodTimer.start();
    });
}

QList<SmaModbusBatteryInverterDiscovery::Result> SmaModbusBatteryInverterDiscovery::discoveryResults() const
{
    return m_discoveryResults;
}

void SmaModbusBatteryInverterDiscovery::checkNetworkDevice(const QHostAddress &address)
{
    qCInfo(dcSma()) << "Checking network device:" << address << "Port:" << m_port << "Slave ID:" << m_modbusAddress;

    SmaBatteryInverterModbusTcpConnection *connection = new SmaBatteryInverterModbusTcpConnection(address, m_port, m_modbusAddress, this);
    m_connections.append(connection);

    connect(connection, &SmaBatteryInverterModbusTcpConnection::reachableChanged, this, [=](bool reachable){
        if (!reachable) {
            cleanupConnection(connection);
            return;
        }

        connect(connection, &SmaBatteryInverterModbusTcpConnection::initializationFinished, this, [=](bool success){
            if (!success) {
                qCInfo(dcSma()) << "Discovery: Initialization failed on" << address.toString() << "Skipping result...";;
                cleanupConnection(connection);
                return;
            }

            if (connection->deviceClass() != Sma::DeviceClassBatteryInverter) {
                qCInfo(dcSma()) << "Discovery: Initialization successful for" << address.toString() << "but the device class is not a battery inverter. Skipping result...";;
                cleanupConnection(connection);
                return;
            }

            Result result;
            result.deviceName = connection->deviceName();
            result.serialNumber = QString::number(connection->serialNumber());
            result.port = m_port;
            result.modbusAddress = m_modbusAddress;
            result.softwareVersion = Sma::buildSoftwareVersionString(connection->softwarePackage());
            result.address = address;
            m_discoveryResults.append(result);

            qCInfo(dcSma()) << "Discovery: --> Found";
            qCInfo(dcSma()) << "  Device name:" << result.deviceName;
            qCInfo(dcSma()) << "  Serial number:" << result.serialNumber;
            qCInfo(dcSma()) << "  Software version:" << result.softwareVersion;
            qCInfo(dcSma()) << " " << result.networkDeviceInfo;

            cleanupConnection(connection);
        });

        if (!connection->initialize()) {
            qCDebug(dcSma()) << "Discovery: Unable to initialize connection on" << address.toString();
            cleanupConnection(connection);
        }
    });

    connect(connection, &SmaBatteryInverterModbusTcpConnection::checkReachabilityFailed, this, [=](){
        qCDebug(dcSma()) << "Discovery: Checking reachability failed on" << address.toString();
        cleanupConnection(connection);
    });

    connection->connectDevice();
}

void SmaModbusBatteryInverterDiscovery::cleanupConnection(SmaBatteryInverterModbusTcpConnection *connection)
{
    m_connections.removeAll(connection);
    connection->disconnectDevice();
    connection->deleteLater();
}

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

    // Fill in all network device infos we have
    for (int i = 0; i < m_discoveryResults.length(); i++)
        m_discoveryResults[i].networkDeviceInfo = m_networkDeviceInfos.get(m_discoveryResults.at(i).address);

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

    qCInfo(dcSma()) << "Discovery: Finished the discovery process. Found" << m_discoveryResults.length()
                    << "SMA battery inverters in" << QTime::fromMSecsSinceStartOfDay(durationMilliSeconds).toString("mm:ss.zzz");
    m_gracePeriodTimer.stop();

    emit discoveryFinished();

}
