//
// Created by xajhu on 2021/8/11 0011.
//
#include <uv.h>
#include <sds/sds.h>

#include "msg_queue.h"
#include "s2j/s2j.h"
#include "config.h"
#include "hardware.h"

static void *j2s_mq_msg(cJSON *pJson) {
    s2j_create_struct_obj(pMsg, MQ_CMD_MSG);
    s2j_struct_get_basic_element(pMsg, pJson, string, cmd);
    s2j_struct_get_basic_element(pMsg, pJson, string, key);
    s2j_struct_get_basic_element(pMsg, pJson, string, value);
    return pMsg;
}

typedef struct {
    char        *buf;
    unsigned int len;
} JM_BUF, *PJM_BUF;

#if 0
static void print_my_jemalloc_data(void *opaque, const char *str) {
    PJM_BUF      pBuf = (PJM_BUF)opaque;
    unsigned int len  = strlen(str);
    char        *buf  = (pBuf->buf == NULL) ? mallocx(len + 1, MALLOCX_TCACHE_NONE)
                                            : rallocx(pBuf->buf, pBuf->len + len + 1, MALLOCX_TCACHE_NONE);
    if (buf == NULL) {
        return;
    }
    memcpy(&buf[pBuf->len], str, len + 1);
    pBuf->buf = buf;
    pBuf->len += len;
}
#endif

static void wait_buf(PJM_BUF pBuf) {
    do {
        unsigned int begin = pBuf->len;
        uv_sleep(1000);
        if (pBuf->len == begin) {
            return;
        }
    } while (TRUE);
}

const char *on_msg_cmd(const char *pCmd) {
    char       *pRsp = NULL;
    PMQ_CMD_MSG pMsg;
    cJSON      *pJson = cJSON_Parse(pCmd);

    if (pJson == NULL) {
        return NULL;
    }

    pMsg = j2s_mq_msg(pJson);

    if (strcmp(pMsg->cmd, "get") == 0) {
        if (strcmp(pMsg->key, "mem_info") == 0) {
#if 0
            JM_BUF jb;

            jb.buf = NULL;
            jb.len = 0;

            malloc_stats_print(print_my_jemalloc_data, &jb, NULL);
            wait_buf(&jb);
#endif
            pRsp = strdup("Unsupport");
            //dallocx(jb.buf, MALLOCX_TCACHE_NONE);
        } else if (strcmp(pMsg->key, "cfg_all") == 0) {
            pRsp = (char *)config_item_dump_fmt(NULL);
        } else if (strcmp(pMsg->key, "sys_info") == 0) {
            pRsp = (char *)get_hardware_json();
        } else {
            sds s = sdsempty();
            s     = sdscatfmt(s, "Unknown key [%s] of command get", pMsg->key);
            pRsp  = strdup(s);
            sdsfree(s);
        }
    } else {
    }

    free(pMsg);
    cJSON_Delete(pJson);
    return pRsp;
}