#include "FormErrorCodeNote.h"
#include "ui_FormErrorCodeNote.h"

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

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

    initWidget();
    initConnect();
}

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

bool FormErrorCodeNote::returnParent()
{
    updateData();
    return ConfigManager::instance()->saveConfig(ERROR_CODE_NOTE, QVariant::fromValue(m_tcu_cfg.error_code_note));
}

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

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

void FormErrorCodeNote::refreshData()
{
    GeneralInterface::clearGridLayoutChiledren(ui->widget_layout);

    for (int index = 0; index < m_tcu_cfg.error_code_note.size(); index ++)    {
        ERROR_NOTE data = m_tcu_cfg.error_code_note[index];
        QLabel *error_note_label = new QLabel(data.error_note);
        error_note_label->setMinimumHeight(48);
        GeneralInterface::gridLayoutAddWidget(ui->widget_layout, error_note_label, index, 0);

        CustomLineEdit *error_code_lineedit = new CustomLineEdit();

        error_code_lineedit->setAlignment(Qt::AlignRight);
        error_code_lineedit->setText(QString("0x%1").arg(QString::number(data.error_code, 16).toUpper()));
        GeneralInterface::gridLayoutAddWidget(ui->widget_layout, error_code_lineedit, index, 1);

        connect(error_code_lineedit, &CustomLineEdit::textChanged, this, [this, &data](const QString& text) {
            bool ok = false;
            if (text.toUInt(&ok, 16) != data.error_code) {
                setIsModify(true);
            }
        } );
    }

    GeneralInterface::gridLayoutAddStrtch(ui->widget_layout);
    ui->widget_layout->setColumnStretch(0, 1);
}

void FormErrorCodeNote::updateData()
{

}

void FormErrorCodeNote::showEvent(QShowEvent *event)
{
    setIsModify(true);
    m_tcu_cfg = ConfigManager::instance()->tcu_cfg();
    refreshData();
    BaseWidget::showEvent(event);
}
