#include "FormLanguageConfig.h"
#include "ui_FormLanguageConfig.h"

#include <QMessageBox>

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

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

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

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

bool FormLanguageConfig::returnParent()
{
    if (m_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.language = getLanguage();
            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 FormLanguageConfig::setLanguage(const int &language)
{
    GeneralInterface::setCheckBoxChecked(this, false);
    switch (language) {
    case Config::Language::SYSTEM:
        ui->system->setChecked(true);
        break;
    case Config::Language::ENGLISH:
        ui->en_us->setChecked(true);
        break;
    case Config::Language::CHINESE:
        ui->zh_ch->setChecked(true);
        break;
    default:
        break;
    }
}

int FormLanguageConfig::getLanguage()
{
    int row = 0;
    QList<QCheckBox*> checkBoxes = this->findChildren<QCheckBox*>();
    foreach (QCheckBox* checkBox, checkBoxes) {
        if (checkBox->isChecked()) {
            row = ui->language_layout->indexOf(checkBox);
        }
    }

    return row;
}

void FormLanguageConfig::showEvent(QShowEvent *event)
{
    m_tcu_cfg = ConfigManager::instance()->tcu_cfg();
    m_isModify = false;
    setLanguage(m_tcu_cfg.language);
    BaseWidget::showEvent(event);
}

void FormLanguageConfig::hideEvent(QHideEvent *event)
{
    BaseWidget::hideEvent(event);
}
