#include <QGuiApplication>
#include <QImage>
#include <QSignalSpy>
#include <QtTest>

#include "icon.h"

using namespace UkuiQuick;

namespace {

QImage makeSolidImage(const QSize &size, const QColor &color)
{
    QImage image(size, QImage::Format_ARGB32);
    image.fill(color);
    return image;
}

}

class icon_test : public QObject
{
    Q_OBJECT

private slots:
    void radiusClampsNegativeValues();
    void radiusClipClearsCornersAndPreservesCenter();
    void radiusLargerThanHalfSizeClampsToHalfSize();
    void radiusEnablesRadiusPath();
    void forceRoundWinsOverRadius();
    void addUnifiedIconBoxWinsOverForceRoundAndRadius();
};

void icon_test::radiusClampsNegativeValues()
{
    Icon icon;
    QSignalSpy radiusSpy(&icon, &Icon::radiusChanged);

    QCOMPARE(icon.radius(), 0);

    icon.setRadius(-5);
    QCOMPARE(icon.radius(), 0);
    QCOMPARE(radiusSpy.count(), 0);

    icon.setRadius(6);
    QCOMPARE(icon.radius(), 6);
    QCOMPARE(radiusSpy.count(), 1);
}

void icon_test::radiusClipClearsCornersAndPreservesCenter()
{
    Icon icon;
    const QImage source = makeSolidImage(QSize(16, 16), QColor(Qt::red));

    const QImage clipped = icon.clipRoundedRect(source, 4);

    QCOMPARE(clipped.pixelColor(8, 8), QColor(Qt::red));
    QCOMPARE(clipped.pixelColor(0, 0).alpha(), 0);
    QCOMPARE(clipped.pixelColor(15, 0).alpha(), 0);
    QCOMPARE(clipped.pixelColor(0, 15).alpha(), 0);
    QCOMPARE(clipped.pixelColor(15, 15).alpha(), 0);
}

void icon_test::radiusLargerThanHalfSizeClampsToHalfSize()
{
    Icon icon;
    const QImage source = makeSolidImage(QSize(16, 16), QColor(Qt::red));

    const QImage clipped = icon.clipRoundedRect(source, 100);
    const QImage expected = icon.clipRoundedRect(source, 8);

    QCOMPARE(clipped, expected);
}

void icon_test::radiusEnablesRadiusPath()
{
    Icon icon;

    QCOMPARE(static_cast<int>(icon.renderPath()), static_cast<int>(Icon::RenderPath::Direct));

    icon.setRadius(6);

    QCOMPARE(static_cast<int>(icon.renderPath()), static_cast<int>(Icon::RenderPath::Radius));
}

void icon_test::forceRoundWinsOverRadius()
{
    Icon icon;

    icon.setRadius(6);
    icon.setForceRound(true);

    QCOMPARE(static_cast<int>(icon.renderPath()), static_cast<int>(Icon::RenderPath::ForceRound));
}

void icon_test::addUnifiedIconBoxWinsOverForceRoundAndRadius()
{
    Icon icon;

    icon.setRadius(6);
    icon.setForceRound(true);
    icon.setAddUnifiedIconBox(true);

    QCOMPARE(static_cast<int>(icon.renderPath()), static_cast<int>(Icon::RenderPath::UnifiedIconBox));
}

int main(int argc, char *argv[])
{
    qputenv("QT_QPA_PLATFORM", "offscreen");
    qputenv("QT_QPA_PLATFORMTHEME", "generic");
    qputenv("QT_FATAL_WARNINGS", "0");
    qputenv("QT_LOGGING_RULES", "qt.qpa.*=false");
    qputenv("GSETTINGS_BACKEND", "memory");

    QGuiApplication app(argc, argv);
    icon_test testCase;
    return QTest::qExec(&testCase, argc, argv);
}

#include "test-icon.moc"
