// 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-energy-plugin-nymea.
*
* nymea-energy-plugin-nymea.s 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-energy-plugin-nymea.s 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-energy-plugin-nymea. If not, see <https://www.gnu.org/licenses/>.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "energymanagerdbusinterface.h"

#include <QDBusConnection>
#include <QLoggingCategory>

Q_DECLARE_LOGGING_CATEGORY(dcNymeaEnergy)

#include "../smartchargingmanager.h"

static const QString kDbusService = QStringLiteral("io.nymea.energymanager");
static const QString kDbusPath = QStringLiteral("/io/nymea/energymanager");

EnergyManagerDbusInterface::EnergyManagerDbusInterface(SmartChargingManager *smartChargingManager, QObject *parent)
    : QObject(parent)
    , m_smartChargingManager(smartChargingManager)
{
    QDBusConnection connection = QDBusConnection::systemBus();

    if (!connection.isConnected()) {
        qCWarning(dcNymeaEnergy()) << "Could not connect to DBus system bus. Energy manager DBus interface not available.";
        return;
    }

    if (!connection.registerService(kDbusService)) {
        qCWarning(dcNymeaEnergy()) << "Failed to register DBus service" << kDbusService << "Energy manager DBus interface not available.";
        return;
    }

    if (!connection.registerObject(kDbusPath, this, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) {
        qCWarning(dcNymeaEnergy()) << "Failed to register DBus object path" << kDbusPath;
        return;
    }

    connect(m_smartChargingManager, &SmartChargingManager::chargingConfigurationAdded, this, [this](const ChargingConfiguration &chargingConfiguration) {
        emit chargingConfigurationAdded(serializeChargingConfiguration(chargingConfiguration));
    });
    connect(m_smartChargingManager, &SmartChargingManager::chargingConfigurationRemoved, this, [this](const ThingId &evChargerId) {
        emit chargingConfigurationRemoved(evChargerId.toString());
    });
    connect(m_smartChargingManager, &SmartChargingManager::chargingConfigurationChanged, this, [this](const ChargingConfiguration &chargingConfiguration) {
        emit chargingConfigurationChanged(serializeChargingConfiguration(chargingConfiguration));
    });

    connect(m_smartChargingManager, &SmartChargingManager::chargingStateAdded, this, [this](const ChargingState &chargingState) {
        emit chargingStateAdded(serializeChargingState(chargingState));
    });
    connect(m_smartChargingManager, &SmartChargingManager::chargingStateRemoved, this, [this](const ThingId &evChargerId) { emit chargingStateRemoved(evChargerId.toString()); });
    connect(m_smartChargingManager, &SmartChargingManager::chargingStateChanged, this, [this](const ChargingState &chargingState) {
        emit chargingStateChanged(serializeChargingState(chargingState));
    });
}

QVariantList EnergyManagerDbusInterface::chargingConfigurations() const
{
    QVariantList configurations;
    if (!m_smartChargingManager) {
        return configurations;
    }

    foreach (const ChargingConfiguration &chargingConfiguration, m_smartChargingManager->chargingConfigurations()) {
        configurations.append(serializeChargingConfiguration(chargingConfiguration));
    }

    return configurations;
}

QVariantList EnergyManagerDbusInterface::chargingStates() const
{
    QVariantList states;
    if (!m_smartChargingManager) {
        return states;
    }

    foreach (const ChargingState &chargingState, m_smartChargingManager->chargingStates()) {
        states.append(serializeChargingState(chargingState));
    }

    return states;
}

QVariantMap EnergyManagerDbusInterface::serializeChargingConfiguration(const ChargingConfiguration &chargingConfiguration) const
{
    QVariantMap map;
    map.insert(QStringLiteral("evChargerId"), chargingConfiguration.evChargerId().toString());
    map.insert(QStringLiteral("assignedCarId"), chargingConfiguration.assignedCarId().toString());

    map.insert(QStringLiteral("chargingMode"), static_cast<int>(chargingConfiguration.chargingMode()));
    map.insert(QStringLiteral("endDateTime"), chargingConfiguration.endDateTime().toString(Qt::ISODate));
    map.insert(QStringLiteral("repeatDays"), QVariant::fromValue(chargingConfiguration.repeatDays()));
    map.insert(QStringLiteral("targetPercentage"), chargingConfiguration.targetPercentage());
    map.insert(QStringLiteral("dailySpotMarketPercentage"), chargingConfiguration.dailySpotMarketPercentage());
    map.insert(QStringLiteral("lockOnUnplug"), chargingConfiguration.lockOnUnplug());

    return map;
}

QVariantMap EnergyManagerDbusInterface::serializeChargingState(const ChargingState &chargingState) const
{
    QVariantMap map;
    map.insert(QStringLiteral("evChargerId"), chargingState.evChargerId().toString());
    map.insert(QStringLiteral("mode"), static_cast<int>(chargingState.mode()));
    map.insert(QStringLiteral("overloadProtectionActive"), chargingState.overloadProtectionActive());
    map.insert(QStringLiteral("targetTimeOvershot"), chargingState.targetTimeOvershot());
    map.insert(QStringLiteral("powerLockSeconds"), chargingState.powerLockSeconds());
    map.insert(QStringLiteral("powerLockDuration"), chargingState.powerLockDuration());
    map.insert(QStringLiteral("batteryLevelConsiderationActive"), chargingState.batteryLevelConsiderationActive());

    return map;
}
