#include <memory>

#include "internal/argh.h"
#include "proto/service.pb.h"
#include <mesytec-mnode/mnode_nng_async.h>
#include <mesytec-mvlc/mesytec-mvlc.h>
#include <mesytec-mvlc/util/signal_handling.h>

using namespace mesytec;
using namespace mesytec::mnode;
using namespace std::literals;

class PingServer: public nng::AsyncRepWork
{
  public:
    explicit PingServer(nng_socket socket)
        : AsyncRepWork(socket)
    {
    }

    nng::unique_msg handle_request(nng::unique_msg &&msg) override
    {
        ping_.ParseFromArray(nng_msg_body(msg.get()), nng_msg_len(msg.get()));
        pong_.set_peer_id(ping_.peer_id());
        pong_.set_sequence_number(ping_.sequence_number());
        ++num_transactions;
        return nng::make_message(pong_.SerializeAsString());
    }

    void report()
    {
        spdlog::info("PingServer, peer_id={}, transactions={}", peer_id, num_transactions);
    }

  private:
    proto::Ping ping_;
    proto::Pong pong_;
    static std::atomic<size_t> next_peer_id;
    size_t peer_id = next_peer_id++;
    size_t num_transactions = 0;
};

std::atomic<size_t> PingServer::next_peer_id;

int main()
{
    spdlog::set_level(spdlog::level::debug);

    auto socket = nng::make_rep_socket();

    if (int res = nng_listen(socket, "tcp://localhost:5555", nullptr, 0))
    {
        nng::mnode_nng_error("nng_listen", res);
        return res;
    }

    mvlc::util::Stopwatch sw;
    std::vector<std::unique_ptr<PingServer>> servers;

    for (int i = 0; i < 10; ++i)
        servers.emplace_back(std::make_unique<PingServer>(socket));

    for (auto &server: servers)
        server->work();

    for (;;)
    {
        std::this_thread::sleep_for(100ms);
        if (sw.get_interval() >= 1s)
        {
            for (auto &server: servers)
                server->report();
            sw.interval();
        }
    }

    return 0;
}
