#include "CustomLineEdit.h"

#include <QInputDialog>
#include <QApplication>
#include <QDebug>

CustomLineEdit::CustomLineEdit(QWidget *parent)
    : QLineEdit(parent)
    , formType(General::Type::VALUE)
{
    setReadOnly(true);// 防止直接输入，强制用对话框输入

    m_input_dialog.reset(new DialogEditValue());
    m_input_dialog->setParent(parent);
    m_input_dialog->setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    m_input_dialog->setWindowModality(Qt::WindowModal);
}

CustomLineEdit::~CustomLineEdit()
{}

bool CustomLineEdit::event(QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        m_input_dialog->setValue(text(), formType);
        m_input_dialog->setEditType(editType);
        auto ret = m_input_dialog->exec();  // 阻塞，直到窗口关闭
        if (ret == QDialog::Accepted) {
            setText(m_input_dialog->getValue(formType));
            updateDisplayText();
        }
    }

    return QLineEdit::event(event);
}

void CustomLineEdit::setEditType(int newEditType)
{
    editType = newEditType;
}

void CustomLineEdit::setFormType(int newFormType)
{
    formType = newFormType;
}

void CustomLineEdit::setDisplayBase(DisplayBase base)
{
    m_displayBase = base;
    updateDisplayText();
}

CustomLineEdit::DisplayBase CustomLineEdit::displayBase() const
{
    return m_displayBase;
}

void CustomLineEdit::updateDisplayText()
{
    bool ok = false;
    int value = text().toInt(&ok, 10); // 假设原始输入为十进制
    if (!ok) {
        setText(""); // 非数字清空
        return;
    }
    switch (m_displayBase) {
    case Base_Decimal:
        setText(QString::number(value, 10));
        break;
    case Base_Hex:
        setText("0x" + QString::number(value, 16).toUpper());
        break;
    case Base_Binary:
        setText("0b" + QString::number(value, 2));
        break;
    }
}
