// 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 "energymanagerconfiguration.h"

#include <nymeasettings.h>

#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonParseError>

#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(dcNymeaEnergy)

EnergyManagerConfiguration::EnergyManagerConfiguration(QObject *parent)
    : QObject{parent}
{
    // Load config for the EM in following order:
    // - ENV
    // - Default path (/var/lib/nymea/energy-manager-configuration.json)
    // - no file loading, start defaults

    qCDebug(dcNymeaEnergy()) << "Checking energy manager configuration...";

    bool loaded = false;

    QString envConfigFilePath = QString(qgetenv("NYMEA_ENERGY_MANAGER_CONFIG"));
    if (!envConfigFilePath.isEmpty()) {
        QFileInfo configFileInfo(envConfigFilePath);
        if (!configFileInfo.exists()) {
            qCWarning(dcNymeaEnergy()) << "The energy manager configuration has been specified in the ENV, but there is no such file:" << envConfigFilePath;
        } else {
            loaded = loadConfiguration(configFileInfo.absoluteFilePath());
        }
    } else if (!loaded) {
        QFileInfo configFileInfo(NymeaSettings::storagePath() + "/energy-manager-configuration.json");
        if (configFileInfo.exists()) {
            loaded = loadConfiguration(configFileInfo.absoluteFilePath());
            if (loaded) {
                qCDebug(dcNymeaEnergy()) << "Loaded the energy manager configuration successfully from" << configFileInfo.absoluteFilePath();
            }
        }
    } else if (!loaded) {
        qCDebug(dcNymeaEnergy()) << "No energy manager configuration found. Using default values.";
    }
}

uint EnergyManagerConfiguration::chargingEnabledLockDuration() const
{
    return m_chargingEnabledLockDuration;
}

uint EnergyManagerConfiguration::chargingCurrentLockDuration() const
{
    return m_chargingCurrentLockDuration;
}

uint EnergyManagerConfiguration::minimumScheduleDuration() const
{
    return m_minimumScheduleDuration;
}

double EnergyManagerConfiguration::spotMarketChargePredictableEnergyPercentage() const
{
    return m_spotMarketChargePredictableEnergyPercentage;
}

bool EnergyManagerConfiguration::loadConfiguration(const QString &filePath)
{
    QFile configFile(filePath);
    if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(dcNymeaEnergy()) << "Failed to open energy manager configuration file" << filePath << ":" << configFile.errorString();
        return false;
    }

    QByteArray data = configFile.readAll();
    configFile.close();

    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        qCWarning(dcNymeaEnergy()) << "Failed to load energy manager configuration, the JSON data seems to be invalid:" << jsonError.errorString();
        return false;
    }

    QVariantMap configMap = jsonDoc.toVariant().toMap();
    if (configMap.contains("chargingEnabledLockDuration"))
        m_chargingEnabledLockDuration = configMap.value("chargingEnabledLockDuration").toUInt();

    if (configMap.contains("chargingCurrentLockDuration"))
        m_chargingCurrentLockDuration = configMap.value("chargingCurrentLockDuration").toUInt();

    if (configMap.contains("minimumScheduleDuration"))
        m_minimumScheduleDuration = configMap.value("minimumScheduleDuration").toUInt();

    if (configMap.contains("spotMarketChargePredictableEnergyPercentage"))
        m_spotMarketChargePredictableEnergyPercentage = configMap.value("spotMarketChargePredictableEnergyPercentage").toDouble();

    return true;
}
