#include "NngDebuger.h"
#include "pe_input/pe_input.h"
#include "rw_zlog.h"
#include <nng/nng.h>
#include <nng/protocol/reqrep0/rep.h>
#include <string>
#include <boost/algorithm/string/trim.hpp>

void NngDebuger::run() {
    nng_socket replier;
    int status = nng_rep0_open(&replier);

    do {
        status = nng_listen(replier, "tcp://172.16.104.70:33892", nullptr, 0);
        if (status != 0) {
            LOGI("amass nng_listen: %d %s", status, nng_strerror(status));
        } else {
            LOGI("amass listen success.");
        }

    } while (status != 0);

    while (!m_exit) {
        char *buffer = nullptr;
        size_t size;
        status = nng_recv(replier, &buffer, &size, NNG_FLAG_ALLOC);

        std::string message(buffer, size);
        boost::trim(message);
        process(message);

        nng_free(buffer, size);

        const char *reply = "World, Hello!";
        nng_send(replier, (void *)reply, strlen(reply) + 1, 0);
    }
}

void NngDebuger::process(const std::string &message) {
    LOGI("amass received: %s", message.c_str());
    if (m_peInput == nullptr) {
        LOGI("amass peInput is null.");
        return;
    }
    if (message == "1") {
        LOGI("amass 1");
        m_peInput->icReaderCallback(0, -1, "");
    } else if (message == "2") {
        m_peInput->icReaderCallback(0, -2, "");
    } else if (message == "3") {
        m_peInput->icReaderCallback(0, -3, "");
    }
}

// /home/amass/Projects/FaceAccess/build/NngDebuger/nngdebuger

NngDebuger::~NngDebuger() {
    m_exit = true;
    if (m_thread && m_thread->joinable()) {
        m_thread->join();
    }
}

void NngDebuger::setPeInput(GPeInput *peInput) {
    m_peInput = peInput;
}

NngDebuger::NngDebuger() {
    m_exit = false;
    m_thread = std::make_shared<std::thread>(&NngDebuger::run, this);
}
