#include "FormTxProfile.h"
#include "ui_FormTxProfile.h"

#include "Globals.h"
#include "ConfigManager.h"
#include "LanguageManager.h"
#include "GeneralInterface.h"

FormTxProfile::FormTxProfile(BaseWidget *parent)
    : BaseWidget(parent)
    , ui(new Ui::FormTxProfile)
{
    ui->setupUi(this);

    initWidget();
    initConnect();
}

FormTxProfile::~FormTxProfile()
{
    delete ui;
}

bool FormTxProfile::returnParent()
{
    return updateData();
}

void FormTxProfile::initWidget()
{
    QStringList kind_list;
    kind_list << ChargingProfiles::Kind::ABSOLUTE
              << ChargingProfiles::Kind::RELATIVE
              << ChargingProfiles::Kind::RECURRING;
    ui->chargingProfileKind->addItems(kind_list);
    ui->chargingProfileKind->setEnabled(false);

    QStringList recurrencyKindList;
    recurrencyKindList << ChargingProfiles::RecurrencyKind::NO_RECURRING
                       << ChargingProfiles::RecurrencyKind::DAILY
                       << ChargingProfiles::RecurrencyKind::WEEKLY;
    ui->recurrencyKind->addItems(recurrencyKindList);
    ui->recurrencyKind->setEnabled(false);

    QStringList rateUnit;
    rateUnit << ChargingProfiles::UnitType::WATT
             << ChargingProfiles::UnitType::AMPERE;
    ui->chargingRateUnit->addItems(rateUnit);

    auto maxStackLevel = ConfigManager::instance()->cfg_key().SmartChargingProfile.ChargeProfileMaxStackLevel;
    refreshStackLevelCombox(maxStackLevel);
}

void FormTxProfile::initConnect()
{
    connect(LanguageManager::instance(), &LanguageManager::languageChanged,     this, [this]() {
        ui->retranslateUi(this);
    });

    connect(ui->chargingRateUnit, &CustomComboBox::currentTextChanged,          this, [this](const QString& text) {
        refreshChargingRateUnit(text);
    });

    connect(GLOBALS, &Globals::ocppConfigKeyValueChanged,                       this, [this](const CONFIG_KEY_INFO& value) {
        if (value.SmartChargingProfile.ChargeProfileMaxStackLevel != ui->stackLevel->count()) {
            refreshStackLevelCombox(value.SmartChargingProfile.ChargeProfileMaxStackLevel);
        }

        ui->stackLevel->setCurrentText(QString::number(m_profile_info.stackLevel));
    });
}

void FormTxProfile::refreshStackLevelCombox(const int &maxStacklevel)
{
    ui->stackLevel->clear();
    for(int index = 0; index <= maxStacklevel; index ++) {
        ui->stackLevel->addItem(QString::number(index));
    }
}

void FormTxProfile::refreshData()
{
    if (m_profile_info.chargingProfilePurpose != ui->chargingProfilePurpose->text()) return;
    ui->connectorID->setText(QString::number(m_profile_info.connectorId));
    ui->stackLevel->setCurrentText(QString::number(m_profile_info.stackLevel));
    ui->chargingProfileKind->setCurrentText(m_profile_info.chargingProfileKind);
    ui->recurrencyKind->setCurrentText(m_profile_info.recurrencyKind);
    ui->startTime->setDateTime(QDateTime::fromString(m_profile_info.chargingSchedule.startTime, Qt::ISODate));
    ui->startPeriod->setText(QString::number(m_profile_info.chargingSchedule.chargingSchedulePeriod[0].startPeriod));
    ui->chargingRateUnit->setCurrentText(m_profile_info.chargingSchedule.chargingRateUnit);
    refreshChargingRateUnit(m_profile_info.chargingSchedule.chargingRateUnit);
}

void FormTxProfile::refreshChargingRateUnit(const QString &curUnit)
{
    QString limitStr = "";
    if (curUnit == ChargingProfiles::UnitType::AMPERE) {
        limitStr = QString("%1 A").arg(QString::number(m_profile_info.chargingSchedule.chargingSchedulePeriod[0].limit / 1000.0, 'f', 2));
    } else if (curUnit == ChargingProfiles::UnitType::WATT) {
        limitStr = QString("%1 KW").arg(QString::number(m_profile_info.chargingSchedule.chargingSchedulePeriod[0].limit / 1000.0, 'f', 2));
    }
    ui->limit->setText(limitStr);
}

bool FormTxProfile::updateData()
{
    m_profile_info.chargingSchedule.startTime                               = ui->startTime->dateTime().toString(Qt::ISODate);
    m_profile_info.chargingSchedule.chargingSchedulePeriod[0].startPeriod   = ui->startPeriod->text().toInt();
    m_profile_info.chargingSchedule.chargingRateUnit                        = ui->chargingRateUnit->currentText();
    m_profile_info.chargingSchedule.chargingSchedulePeriod[0].limit         = ui->limit->text().split(" ")[0].toDouble() * 1000;
    m_profile_info.stackLevel                                               = ui->stackLevel->currentText().toInt();

    CHARGING_PROFILES profile_infos = ConfigManager::instance()->charging_profiles();
    for(int index = 0; index < profile_infos.chargingProfiles.size(); index ++) {
        if (profile_infos.chargingProfiles[index].chargingProfilePurpose == m_profile_info.chargingProfilePurpose &&
            profile_infos.chargingProfiles[index].chargingProfileId == m_profile_info.chargingProfileId) {
            profile_infos.chargingProfiles[index] = m_profile_info;
        }
    }

    return ConfigManager::instance()->saveConfig(CHARGING_PROFILE, QVariant::fromValue(profile_infos));
}

void FormTxProfile::showEvent(QShowEvent *event)
{
    setIsModify(false);
    refreshData();
    BaseWidget::showEvent(event);
}

charging_profiles_detail_info_t FormTxProfile::profile_info() const
{
    return m_profile_info;
}

void FormTxProfile::setProfile_info(charging_profiles_detail_info_t newProfile_info)
{
    m_profile_info = newProfile_info;
}
