#include "FormPcuhwSettings.h"
#include "ui_FormPcuhwSettings.h"

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

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

    GeneralInterface::setTouchScroller(ui->scrollArea);
    initWidget();
}

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

bool FormPcuhwSettings::returnParent()
{
    m_pcuhw_cfg = getNewData();
    CCU_CFG ccu_cfg = ConfigManager::instance()->ccu_cfg();
    ccu_cfg.pcuhw = m_pcuhw_cfg;

    return ConfigManager::instance()->saveConfig(CCU_CONFIG, QVariant::fromValue(ccu_cfg));
}

void FormPcuhwSettings::initWidget()
{
    ui->connect_ip_string->setFormType(General::Type::IP_ADDR);
}

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

void FormPcuhwSettings::connectAllValueChanged(QWidget *widget)
{
    // QLineEdit
    if (auto edit = qobject_cast<CustomLineEdit*>(widget)) {
        connect(edit, &QLineEdit::textChanged,                      this, &FormPcuhwSettings::onValueChanged);
    }
    // CustomLineEdit
    else if (auto edit = qobject_cast<CustomLineEdit*>(widget)) {
        connect(edit, &CustomLineEdit::textChanged,                 this, &FormPcuhwSettings::onValueChanged);
    }
    // CustomSpinBox
    else if (auto spin = qobject_cast<CustomSpinBox*>(widget)) {
        connect(spin, QOverload<int>::of(&QSpinBox::valueChanged),  this, &FormPcuhwSettings::onValueChanged);
    }
    // QCheckBox
    else if (auto check = qobject_cast<QCheckBox*>(widget)) {
        connect(check, &QCheckBox::stateChanged,                    this, &FormPcuhwSettings::onValueChanged);
    }

    // 递归遍历所有子控件
    auto list = widget->findChildren<QWidget*>();
    for (auto child : std::as_const(list)) {
        connectAllValueChanged(child);
    }
}

void FormPcuhwSettings::refreshData()
{
    ui->enable->setChecked(m_pcuhw_cfg.enable);
    ui->connect_ip_string->setText(m_pcuhw_cfg.connect_ip_string);
    ui->connect_port->setValue(m_pcuhw_cfg.connect_port);
    ui->enable_ssl->setChecked(m_pcuhw_cfg.enable_ssl);
}

PCUHW_CFG FormPcuhwSettings::getNewData()
{
    PCUHW_CFG data;
    data.enable             = ui->enable->isChecked();
    data.connect_ip_string  = ui->connect_ip_string->text();
    data.connect_port       = ui->connect_port->value();
    data.enable_ssl         = ui->enable_ssl->isChecked();

    return data;
}

void FormPcuhwSettings::onValueChanged()
{
    setIsModify(true);
}

void FormPcuhwSettings::showEvent(QShowEvent *event)
{
    setIsModify(false);
    m_pcuhw_cfg = ConfigManager::instance()->ccu_cfg().pcuhw;
    refreshData();
    BaseWidget::showEvent(event);
}
