#include "test_producer_consumer.h"
#include <nng/protocol/pubsub0/sub.h>
#include <thread>
#include <iostream>

int main(int argc, char *argv[])
{
    spdlog::set_level(spdlog::level::info);

    nng_socket subSocket = NNG_SOCKET_INITIALIZER;

    if (int res = nng_sub0_open(&subSocket))
        mnode_nng_fatal("nng_sub0_open", res);

    //if (int res = nng_socket_set_string(subSocket, NNG_OPT_SUB_SUBSCRIBE, ""))
    //    mnode_nng_fatal("consumer socket subscribe", res);

    if (int res = nng_socket_set(subSocket, NNG_OPT_SUB_SUBSCRIBE, nullptr, 0))
        mnode_nng_fatal("consumer socket subscribe", res);

    if (int res = nng_dial(subSocket, "tcp://127.0.0.1:42777", nullptr, 0))
        mnode_nng_fatal("nng_dial tcp", res);

    while (true)
    {
        std::cout << "Waiting for incoming message...\n";
        nng_msg *msg = nullptr;

        if (auto res = receive_message(subSocket, &msg))
        {
            if (res != NNG_ETIMEDOUT)
                mnode_nng_fatal("receive_message", res);
            spdlog::warn("consumer timed out in recv");
            continue;
        }

        fmt::print("Received message of size {}\n", nng_msg_len(msg));

        nng_msg_free(msg);
    }

    return 0;
}
