#include <QSignalSpy>
#include <QtTest>

#include "config-property-map.h"

using namespace UkuiQuick;

class TestableConfigPropertyMap : public ConfigPropertyMap
{
public:
    explicit TestableConfigPropertyMap(Config *config) : ConfigPropertyMap(config) {}
    using ConfigPropertyMap::updateValue;
};

class config_property_map_test : public QObject
{
    Q_OBJECT

private slots:
    void constructorLoadsExistingConfigKeys();
    void configChangesUpdatePropertyMap();
    void qmlSideUpdateWritesBackToConfig();
};

void config_property_map_test::constructorLoadsExistingConfigKeys()
{
    Config config(QVariantMap {
        {QStringLiteral("name"), QStringLiteral("launcher")},
        {QStringLiteral("size"), 32}
    }, static_cast<QObject *>(nullptr));

    TestableConfigPropertyMap map(&config);

    QCOMPARE(map.value(QStringLiteral("name")).toString(), QStringLiteral("launcher"));
    QCOMPARE(map.value(QStringLiteral("size")).toInt(), 32);
}

void config_property_map_test::configChangesUpdatePropertyMap()
{
    Config config(QVariantMap {
        {QStringLiteral("name"), QStringLiteral("launcher")}
    }, static_cast<QObject *>(nullptr));
    TestableConfigPropertyMap map(&config);

    config.setValue(QStringLiteral("name"), QStringLiteral("panel"));
    config.setValue(QStringLiteral("enabled"), true);

    QCOMPARE(map.value(QStringLiteral("name")).toString(), QStringLiteral("panel"));
    QCOMPARE(map.value(QStringLiteral("enabled")).toBool(), true);
}

void config_property_map_test::qmlSideUpdateWritesBackToConfig()
{
    Config config(QVariantMap {
        {QStringLiteral("count"), 1}
    }, static_cast<QObject *>(nullptr));
    TestableConfigPropertyMap map(&config);
    QSignalSpy changedSpy(&config, &Config::configChanged);

    QCOMPARE(map.updateValue(QStringLiteral("count"), 2).toInt(), 2);

    QCOMPARE(config.getValue(QStringLiteral("count")).toInt(), 2);
    QCOMPARE(changedSpy.count(), 1);
    QCOMPARE(changedSpy.first().at(0).toString(), QStringLiteral("count"));
}

QTEST_GUILESS_MAIN(config_property_map_test)

#include "test-config-property-map.moc"
