#include "message_bus/pipeline/stages/3_filters/ProtocolParseFilter.h"

#include <QtTest/QtTest>

#include <QDir>
#include <QFile>
#include <variant>

#include "core/models/DOMMessage.h"
using softbus::message_bus::pipeline::stages::filters::ProtocolParseFilter;

class ProtocolParseFilterTest : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();
    void parses_multiple_dom_messages();

private:
    QString m_cfgDir;
};

void ProtocolParseFilterTest::initTestCase()
{
    m_cfgDir = QDir::tempPath() + QStringLiteral("/softbus_test_cfg");
    QDir().mkpath(m_cfgDir);

    QFile mf(m_cfgDir + QStringLiteral("/metadata_dictionary.json"));
    QVERIFY(mf.open(QIODevice::WriteOnly | QIODevice::Truncate));
    mf.write(R"({
      "metadatas":[
        {"metadataId":"MD_TEMP_001","name":"Temp","description":"t","domain":"PROCESS_PARAM","semanticType":"FLOAT64","unit":"C","minValue":-40,"maxValue":180,"deadband":0.1,"isWriteable":false},
        {"metadataId":"MD_PRESS_001","name":"Press","description":"p","domain":"PROCESS_PARAM","semanticType":"FLOAT64","unit":"MPa","minValue":0,"maxValue":25,"deadband":0.01,"isWriteable":false}
      ]
    })");
    mf.close();

    QFile pf(m_cfgDir + QStringLiteral("/device_profiles.json"));
    QVERIFY(pf.open(QIODevice::WriteOnly | QIODevice::Truncate));
    pf.write(R"({
      "profiles":[
        {"deviceId":"devA","protocol":"modbus_rtu","mappings":[
          {"pointId":"temperature","metadataId":"MD_TEMP_001","byteOffset":0,"byteLength":4,"rawType":"INT32","endianness":"BIG_ENDIAN","scaleFactor":1.0,"offsetFactor":0.0,"expression":"x*0.1"},
          {"pointId":"pressure","metadataId":"MD_PRESS_001","byteOffset":4,"byteLength":4,"rawType":"INT32","endianness":"BIG_ENDIAN","scaleFactor":1.0,"offsetFactor":0.0,"expression":"x*0.001"}
        ]}
      ]
    })");
    pf.close();

    qputenv("SOFTBUS_CONFIG_DIR", m_cfgDir.toUtf8());
}

void ProtocolParseFilterTest::parses_multiple_dom_messages()
{
    ProtocolParseFilter filter;
    softbus::core::models::DOMMessage msg;
    msg.messageId = QStringLiteral("devA.temperature");
    msg.value = 25.5;
    msg.quality = softbus::core::models::DataQuality::GOOD;
    QVERIFY(filter.process(msg));
    auto enriched = filter.enrich(msg);
    QCOMPARE(enriched.sourceMessageId, msg.messageId);
    QCOMPARE(std::get<double>(enriched.engineeringValue), 25.5);
}

QTEST_MAIN(ProtocolParseFilterTest)
#include "protocol_parse_filter_test.moc"
