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

PcElectricDiscovery::PcElectricDiscovery(NetworkDeviceDiscovery *networkDeviceDiscovery, quint16 port, quint16 modbusAddress, QObject *parent)
    : QObject{parent},
    m_networkDeviceDiscovery{networkDeviceDiscovery},
    m_port{port},
    m_modbusAddress{modbusAddress}
{

}

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


void PcElectricDiscovery::startDiscovery()
{
    qCInfo(dcPcElectric()) << "Discovery: Start searching for PCE wallboxes in the network...";
    m_startDateTime = QDateTime::currentDateTime();

    NetworkDeviceDiscoveryReply *discoveryReply = m_networkDeviceDiscovery->discover();
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::hostAddressDiscovered, this, &PcElectricDiscovery::checkNetworkDevice);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, discoveryReply, &NetworkDeviceDiscoveryReply::deleteLater);
    connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){

        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(dcPcElectric()) << "Discovery: Grace period timer triggered.";
            finishDiscovery();
        });
    });
}

void PcElectricDiscovery::checkNetworkDevice(const QHostAddress &address)
{
    EV11ModbusTcpConnection *connection = new EV11ModbusTcpConnection(address, m_port, m_modbusAddress, this);
    m_connections.append(connection);

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

        // Modbus TCP connected...ok, let's try to initialize it!
        connect(connection, &EV11ModbusTcpConnection::initializationFinished, this, [=](bool success){
            if (!success) {
                qCDebug(dcPcElectric()) << "Discovery: Initialization failed on" << address.toString() << "Continue...";;
                cleanupConnection(connection);
                return;
            }

            // Parse the mac address from the registers and compair with the network device info mac address.
            // If they match, we most likly found a PCE wallbox

            QByteArray macRawData;
            QDataStream stream(&macRawData, QIODevice::WriteOnly);
            for (int i = 0; i < connection->macAddress().length(); i++)
                stream << connection->macAddress().at(i);

            MacAddress registerMacAddress(macRawData);
            qCDebug(dcPcElectric()) << "Fetched mac address" << macRawData.toHex() << registerMacAddress;

            // According to PCE the HW revision must be 0
            if (!registerMacAddress.isNull() && connection->hardwareRevision() == 0) {

                // Parse the serial number
                QByteArray serialRawData;
                QDataStream stream(&serialRawData, QIODevice::ReadWrite);
                stream << static_cast<quint16>(0);
                for (int i = 0; i < connection->serialNumber().length(); i++)
                    stream << connection->serialNumber().at(i);

                quint64 serialNumber = serialRawData.toHex().toULongLong(nullptr, 16);
                qCDebug(dcPcElectric()) << "Serial number" << serialRawData.toHex() << serialNumber;

                Result result;
                result.serialNumber = QString::number(serialNumber);
                result.firmwareRevision = connection->firmwareRevision();
                result.address = address;
                result.registerMacAddress = registerMacAddress;
                m_potentialResults.append(result);
            }

            // Done with this connection
            cleanupConnection(connection);
        });

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

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

    // If check reachability failed...skip this host...
    connect(connection, &EV11ModbusTcpConnection::checkReachabilityFailed, this, [=](){
        qCDebug(dcPcElectric()) << "Discovery: Check reachability failed on" << address.toString() << "Continue...";;
        cleanupConnection(connection);
    });

    // Try to connect, maybe it works, maybe not...
    connection->connectDevice();
}

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

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

    for (int i = 0; i < m_potentialResults.length(); i++) {
        const NetworkDeviceInfo networkDeviceInfo = m_networkDeviceInfos.get(m_potentialResults.at(i).address);
        m_potentialResults[i].networkDeviceInfo = networkDeviceInfo;

        Result result = m_potentialResults.at(i);
        if (networkDeviceInfo.macAddressInfos().hasMacAddress(result.registerMacAddress)) {
            qCInfo(dcPcElectric()) << "Discovery: --> Found EV11.3"
                                   << "Serial number:" << result.serialNumber
                                   << "Firmware revision:" << result.firmwareRevision
                                   << result.networkDeviceInfo;
            m_results.append(result);
        } else {
            qCWarning(dcPcElectric()) << "Discovery: --> Found potential EV11.3, but not adding to the results due to imcomplete MAC address check:"
                                      << "Serial number:" << result.serialNumber
                                      << "Firmware revision:" << result.firmwareRevision
                                      << result.networkDeviceInfo;
        }
    }

    m_potentialResults.clear();
    m_networkDeviceInfos.clear();

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

    qCInfo(dcPcElectric()) << "Discovery: Finished the discovery process. Found" << m_results.length()
                           << "PCE wallboxes in" << QTime::fromMSecsSinceStartOfDay(durationMilliSeconds).toString("mm:ss.zzz");
    emit discoveryFinished();
}
