// SPDX-FileCopyrightText: 2020 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "cspinbox.h"

#include <QLineEdit>
#include <QTimer>
#include <QKeyEvent>
#include <QDebug>

#include "frame/cviewmanagement.h"
#include "frame/cgraphicsview.h"
#include "application.h"

const int NormalMode_Height = 36;
const int CompactMode_Height = 24;

CSpinBox::CSpinBox(DWidget *parent)
    : DSpinBox(parent)
{
    qDebug() << "Initializing CSpinBox";
    setFocusPolicy(Qt::StrongFocus);
    if (Application::isTabletSystemEnvir()) {
        qDebug() << "Tablet environment detected, setting read-only mode";
        lineEdit()->setReadOnly(true);
        setEnabledEmbedStyle(false);
        setButtonSymbols(PlusMinus);
    } else {
        qDebug() << "Desktop environment, setting embedded style";
        setEnabledEmbedStyle(true);
        setButtonSymbols(UpDownArrows);
        setMaximumWidth(86);
    }

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    connect(this, &DSpinBox::valueChanged, this, [=](int value) {
#else
    connect(this, QOverload<int>::of(&DSpinBox::valueChanged), this, [=](int value) {
#endif
        setSpinPhaseValue(value, isTimerRunning() ? EChangedUpdate : EChanged);
        updateMaxSize();
    });

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    connect(this, &DSpinBox::valueChanged, this, [=](int value) {
#else
    connect(this, QOverload<int>::of(&DSpinBox::valueChanged), this, [=](int value) {
#endif
        Q_UNUSED(value);
        //if (_keepFocus)
        //this->setFocus();
    },
    Qt::QueuedConnection);

#ifdef DTKWIDGET_CLASS_DSizeMode
    if (DGuiApplicationHelper::instance()->sizeMode() == DGuiApplicationHelper::NormalMode) {
        qDebug() << "Setting normal mode height:" << NormalMode_Height;
        setMaximumHeight(NormalMode_Height);
    } else {
        qDebug() << "Setting compact mode height:" << CompactMode_Height;
        setMaximumHeight(CompactMode_Height);
    }

    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, [=](DGuiApplicationHelper::SizeMode sizeMode) {
        qDebug() << "Size mode changed to:" << (sizeMode == DGuiApplicationHelper::NormalMode ? "Normal" : "Compact");
        if (sizeMode == DGuiApplicationHelper::NormalMode) {
            setMaximumHeight(NormalMode_Height);
        } else {
            setMaximumHeight(CompactMode_Height);
        }
    });
#else
    qDebug() << "Setting default height: 36";
    setMaximumHeight(36);
#endif

    setKeyboardTracking(false);

    setRange(-INT_MAX, INT_MAX);

    lineEdit()->setAlignment(Qt::AlignCenter);
    lineEdit()->installEventFilter(this);
}

bool CSpinBox::isTimerRunning()
{
    bool running = (_wheelTimer != nullptr && _wheelTimer->isActive());
    qDebug() << "Timer running status:" << running;
    return running;
}

bool CSpinBox::isChangedByWheelEnd()
{
    return _wheelEnd;
}

void CSpinBox::setValueChangedKeepFocus(bool b)
{
    _keepFocus = b;
}

void CSpinBox::setSpinRange(int min, int max)
{
    qDebug() << "Setting spin range - min:" << min << "max:" << max;
    m_min = min;
    m_max = max;
}

void CSpinBox::setSpecialText(QString sp)
{
    qDebug() << "Setting special text:" << sp;
    this->blockSignals(true);
    this->setValue(this->minimum());
    this->setSpecialValueText(sp);
    this->blockSignals(false);
}

void CSpinBox::focusInEvent(QFocusEvent *event)
{
//    if (CManageViewSigleton::GetInstance()->getCurView() != nullptr)
//        CManageViewSigleton::GetInstance()->getCurView()->disableCutShortcut(true);
    DSpinBox::focusInEvent(event);
}

void CSpinBox::focusOutEvent(QFocusEvent *event)
{
//    if (CManageViewSigleton::GetInstance()->getCurView() != nullptr)
//        CManageViewSigleton::GetInstance()->getCurView()->disableCutShortcut(false);
    DSpinBox::focusOutEvent(event);
}

void CSpinBox::wheelEvent(QWheelEvent *event)
{
    if (hasFocus()) {
        //启动定时器
        timerStart();

        DSpinBox::wheelEvent(event);
    }
}

void CSpinBox::showEvent(QShowEvent *event)
{
    setValueChangedKeepFocus(true);

    updateMaxSize();
    DSpinBox::showEvent(event);
}

void CSpinBox::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up) {
        //启动定时器
        timerStart();
    } else if (event->key() == Qt::Key_Minus) {
        //不允许负数值设置
        return;
    }
    DSpinBox::keyPressEvent(event);
    event->accept();
    setFocus();
}

void CSpinBox::keyReleaseEvent(QKeyEvent *event)
{
    //timerEnd();
    DSpinBox::keyReleaseEvent(event);
    event->accept();
    setFocus();
}

void CSpinBox::contextMenuEvent(QContextMenuEvent *event)
{
    Q_UNUSED(event)
    // [41555] spinbox 触摸长按会弹出菜单导致焦点丢失，此处截获弹出菜单事件
}

void CSpinBox::mouseDoubleClickEvent(QMouseEvent *event)
{
    // [BUG:45463] 选中两个不同锚点的星形，点击锚点减小按钮，能切换窗口大小
    DSpinBox::mouseDoubleClickEvent(event);
    event->accept();
}

bool CSpinBox::eventFilter(QObject *o, QEvent *e)
{
    if (lineEdit() == o) {
        if (e->type() == QEvent::FontChange) {
            updateMaxSize();
        }
    }
    return DSpinBox::eventFilter(o, e);
}

void CSpinBox::timerEnd()
{
    //先结束timer(标志着isTimerRunning返回false)
    if (_wheelTimer != nullptr) {
        _wheelTimer->deleteLater();
        _wheelTimer = nullptr;
    }

    //wheel结束时的值变化标记
    _wheelEnd = true;
    setSpinPhaseValue(value(), EChangedFinished);
    _wheelEnd = false;
    setFocus();
}

QTimer *CSpinBox::getTimer()
{
    if (_wheelTimer == nullptr) {
        _wheelTimer = new QTimer(this);
        _wheelTimer->setSingleShot(true);
        connect(_wheelTimer, &QTimer::timeout, this, &CSpinBox::timerEnd);
    }
    return _wheelTimer;
}

void CSpinBox::setSpinPhaseValue(int value, EChangedPhase phase)
{
    if (_s_value != value || _s_phase != phase) {
        qDebug() << "Setting spin phase value:" << value << "phase:" << phase;
        _s_value = value;
        _s_phase = phase;

        if (_s_value < m_min) {
            qDebug() << "Value below minimum, adjusting to:" << m_min;
            _s_value = m_min;
        } else if (value > m_max) {
            qDebug() << "Value above maximum, adjusting to:" << m_max;
            _s_value = m_max;
        }
        this->blockSignals(true);
        setValue(_s_value);
        this->blockSignals(false);
        emit valueChanged(_s_value, EChangedPhase(_s_phase));
    }
}

void CSpinBox::updateMaxSize()
{
    if (Application::isTabletSystemEnvir()) {
        const int c_MinWidth = 120;
        int w;

#if (QT_VERSION_MAJOR == 5)
	w = lineEdit()->fontMetrics().width(lineEdit()->text());
#elif (QT_VERSION_MAJOR == 6)
	w = lineEdit()->fontMetrics().horizontalAdvance(lineEdit()->text());
#endif
        qDebug() << "Updating max size for tablet - text width:" << w << "min width:" << c_MinWidth;
        setMaximumWidth(w + c_MinWidth);
    }
}

QSize CSpinBox::sizeHint() const
{
    return DSpinBox::sizeHint();
}

QSize CSpinBox::minimumSizeHint() const
{
    return DSpinBox::minimumSizeHint();
}

void CSpinBox::timerStart()
{
    if (!isTimerRunning()) {
        qDebug() << "Starting timer with initial value:" << value();
        setSpinPhaseValue(value(), EChangedBegin);
    }
    getTimer()->start(300);
}
