#include "internal/mana_nng.hpp"
#include "internal/rxi/log.hpp"

using namespace mesytec::mnode;
using namespace mesytec::mnode::mana;

class Plugin: public IManaPlugin
{
  public:
    explicit Plugin(nng_socket socket)
        : socket_(socket)
    {
    }

    ~Plugin() override
    {
        if (nng_socket_id(socket_) >= 0)
        {
            nng_close(socket_);
            socket_ = NNG_SOCKET_INITIALIZER;
        }
    }

    std::unique_ptr<IManaSink> makeSink() override
    {
        return std::make_unique<NngServerSink>(socket_);
    }

  private:
    nng_socket socket_;
};

MANA_CPP_PLUGIN()
{
    static Plugin *plugin;
    static const char *listenUrl = "ipc:///tmp/mana_nng_server.socket";

    if (plugin)
    {
        log_warn("plugin already created");
        return plugin;
    }

    nng_socket socket = nng::make_pair_socket();
    if (int res = nng_listen(socket, listenUrl, nullptr, 0))
    {
        nng::mnode_nng_error("nng_listen", res);
        return nullptr;
    }

    log_info("listening on %s", listenUrl);

    return plugin = new Plugin(socket);
}
