#include "FormPasswordManage.h"
#include "ui_FormPasswordManage.h"

#include <QMessageBox>

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

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

    setStyleSheet("QLineEdit { "
                  "background-color: #3A3A3F; "
                  "color: white;"
                  "border-radius: 5px;"
                  "}");

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

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

bool FormPasswordManage::returnParent()
{
    if (isModify()) {
        auto ret = QMessageBox::question(this, tr("Save"),
                                         tr("The content has been modified. Do you want to save the changes?"),
                                         QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes);
        if (ret == QMessageBox::Yes) {      // save
            m_tcu_cfg.admin_cfg.password = ui->admin_pwd->text();
            m_tcu_cfg.operator_cfg.password = ui->operator_pwd->text();
            return ConfigManager::instance()->saveConfig(TCU_CONFIG, QVariant::fromValue<TCU_CFG>(m_tcu_cfg));
        } else if (ret == QMessageBox::No){ // no save
            return true;
        } else {                            // cancel
            return false;
        }
    }

    return true;
}

void FormPasswordManage::updatePassword()
{
    setIsModify(false);
    m_tcu_cfg = ConfigManager::instance()->tcu_cfg();
    ui->operator_pwd->setText(m_tcu_cfg.operator_cfg.password);
    ui->admin_pwd->setText(m_tcu_cfg.admin_cfg.password);
}

void FormPasswordManage::showEvent(QShowEvent *event)
{
    updatePassword();
    QWidget::showEvent(event);
}
