#include "trygvis/sensor.h"
#include "trygvis/sensor/io.h"

#define BOOST_TEST_MODULE "SampleTest"

#include <boost/test/unit_test.hpp>

using namespace trygvis::sensor;
using namespace trygvis::sensor::io;
using namespace std;
using namespace boost;

BOOST_AUTO_TEST_CASE(key_value_parser) {
    KeyDictionary dict;

    auto buffer = make_shared<VectorSampleOutputStream>();

    auto parser = make_shared<KeyValueSampleStreamParser>(buffer, dict);

    char data[] = "a=1,   b=2, c=3\n";
    auto buf = boost::asio::buffer(data, sizeof(data));
    parser->process(buf);
    BOOST_CHECK_EQUAL(buffer->samples.size(), 1);
    BOOST_CHECK_EQUAL(dict.size(), 3);
    auto it = dict.begin();
    BOOST_CHECK_EQUAL((*it)->name, "a");
    BOOST_CHECK_EQUAL((*it++)->index, 0);
    BOOST_CHECK_EQUAL((*it)->name, "b");
    BOOST_CHECK_EQUAL((*it++)->index, 1);
    BOOST_CHECK_EQUAL((*it)->name, "c");
    BOOST_CHECK_EQUAL((*it++)->index, 2);
}

BOOST_AUTO_TEST_CASE(key_value_parser2) {
    KeyDictionary dict;

    auto buffer = make_shared<VectorSampleOutputStream>();

    auto parser = make_shared<KeyValueSampleStreamParser>(buffer, dict);

    char data[] = "now=1,sensor 1=0.000999999833333\n";
    auto buf = boost::asio::buffer(data, sizeof(data));
    parser->process(buf);
    BOOST_CHECK_EQUAL(buffer->samples.size(), 1);
    SampleRecord& sample = buffer->samples[0];
    BOOST_CHECK_EQUAL(dict.size(), 2);
    auto it = dict.begin();
    BOOST_CHECK_EQUAL((*it)->name, "now");
    BOOST_CHECK_EQUAL(!sample.at(*it).operator!(), true);
    BOOST_CHECK_EQUAL(sample.at(*it).get(), "1");
    BOOST_CHECK_EQUAL((*it++)->index, 0);

    BOOST_CHECK_EQUAL((*it)->name, "sensor 1");
    BOOST_CHECK_EQUAL(!sample.at(*it).operator!(), true);
    BOOST_CHECK_EQUAL(sample.at(*it).get(), "0.000999999833333");
    BOOST_CHECK_EQUAL((*it++)->index, 1);
}

BOOST_AUTO_TEST_CASE(key_value_parser_with_custom_dict) {
    KeyDictionary dict;

    dict.indexOf("c");
    dict.indexOf("b");

    auto buffer = make_shared<VectorSampleOutputStream>();

    auto parser = make_shared<KeyValueSampleStreamParser>(buffer, dict);

    char data[] = "a=1,   b=2, c=3\n";
    auto buf = boost::asio::buffer(data, sizeof(data));
    parser->process(buf);
    BOOST_CHECK_EQUAL(buffer->samples.size(), 1);
    BOOST_CHECK_EQUAL(dict.size(), 3);
    auto it = dict.begin();
    BOOST_CHECK_EQUAL((*it)->name, "c");
    BOOST_CHECK_EQUAL((*it++)->index, 0);
    BOOST_CHECK_EQUAL((*it)->name, "b");
    BOOST_CHECK_EQUAL((*it++)->index, 1);
}

BOOST_AUTO_TEST_CASE(type_detection_key_value) {
    KeyDictionary dict;

    auto output = make_shared<VectorSampleOutputStream>();

    auto parser = open_sample_stream_parser(output, dict);

    char data[] = "a=1,   b=2, c=3\n";
    auto buf = boost::asio::buffer(data, sizeof(data));
    parser->process(buf);

}