/*
* Copyright (C) 2019 ~ 2026 Deepin Technology Co., Ltd.
*
* Author:     xiepengfei <xiepengfei@uniontech.com>
* Maintainer: xiepengfei <xiepengfei@uniontech.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*/

#include "commonlywidget.h"

#include <gtest/gtest.h>
#include <QMouseEvent>
#include <QFontMetrics>
#include <QTest>

class ut_commonlywidget_test : public ::testing::Test
{
protected:
    void SetUp() override;
    void TearDown() override;

    CommonlyWidget *m_widget = nullptr;
};

void ut_commonlywidget_test::SetUp()
{
    // 构造一个带箭头与不带箭头两种形态以覆盖不同分支
    m_widget = new CommonlyWidget(false, QString(), QStringLiteral("测试"));
}

void ut_commonlywidget_test::TearDown()
{
    if (m_widget) {
        delete m_widget;
        m_widget = nullptr;
    }
}

TEST_F(ut_commonlywidget_test, constructor)
{
    ASSERT_TRUE(m_widget != nullptr);
}

TEST_F(ut_commonlywidget_test, paintEvent)
{
    // 触发 paintEvent，覆盖默认（非 hover）绘制分支
    { QPaintEvent e(m_widget->rect()); m_widget->paintEvent(&e); }
}

TEST_F(ut_commonlywidget_test, paintEventWithArrow)
{
    CommonlyWidget arrow(true, QString(), QStringLiteral("arrow"));
    { QPaintEvent e(arrow.rect()); arrow.paintEvent(&e); }
}

TEST_F(ut_commonlywidget_test, enterEvent)
{
    QEnterEvent enter(QPointF(0, 0), QPointF(0, 0), QPointF(0, 0));
    QTest::ignoreMessage(QtDebugMsg, "Mouse entered widget");
    QCoreApplication::sendEvent(m_widget, &enter);
    { QPaintEvent e(m_widget->rect()); m_widget->paintEvent(&e); }
}

TEST_F(ut_commonlywidget_test, leaveEvent)
{
    QEvent leave(QEvent::Leave);
    QTest::ignoreMessage(QtDebugMsg, "Mouse left widget");
    QCoreApplication::sendEvent(m_widget, &leave);
    { QPaintEvent e(m_widget->rect()); m_widget->paintEvent(&e); }
}

TEST_F(ut_commonlywidget_test, mouseReleaseEvent)
{
    QMouseEvent release(QEvent::MouseButtonRelease, QPointF(10, 10),
                        Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
    bool clicked = false;
    QObject::connect(m_widget, &CommonlyWidget::clicked, [&clicked]() { clicked = true; });
    QTest::ignoreMessage(QtDebugMsg, "CommonlyWidget clicked, emitting signal");
    QCoreApplication::sendEvent(m_widget, &release);
    EXPECT_TRUE(clicked);
}

TEST_F(ut_commonlywidget_test, editorText)
{
    QFontMetrics fm(m_widget->font());
    QString result = m_widget->editorText(fm, QStringLiteral("abcdefghijklmnopqrstuvwxyz"));
    EXPECT_FALSE(result.isEmpty());
}
