#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pair.h"
#include "nn.h"
#include "ev.h"
#include "mqtt_api.h"
typedef struct 
{
    int n;          
    int s;          
}kk_nanomsg_t;
typedef struct 
{
    kk_nanomsg_t handle;
}kk_nanomsg_handle_t;
static kk_nanomsg_handle_t s_msgHdl;
#define NANOMSG_ADDR  "ipc://b2a_loop"

int KK_Sendto_DevData(const char *data, int len)
{
	kk_nanomsg_handle_t *msgHdl = &s_msgHdl;
	if(len <= 0||data == NULL)
	{
		return -1;
	}

    int length = len + 1;
    unsigned char *udata = nn_allocmsg(length, 0);
    if (NULL != udata) 
	{
        memcpy(udata, data, length);
        nn_send(msgHdl->handle.n, &udata, NN_MSG, NN_DONTWAIT);
		INFO_PRINT("KK_data_send:%s \r\n\r\n", udata);
    }	
	
}

int KK_Sendto_CloudData(const char *data, int len)
{
	if(len <= 0||data == NULL)
	{
		return -1;
	}
	return KK_MQTT_SendMsg(TOPIC,data,len);
	
}
static void kk_data_cb (struct ev_loop *loop ,struct ev_io *w, int revents)
{
	unsigned char *dat = NULL;
    void *user_data = ev_userdata(loop);
    kk_nanomsg_handle_t *msgHdl = (kk_nanomsg_handle_t *)user_data;

    unsigned int bytes = nn_recv(msgHdl->handle.n, &dat, NN_MSG, NN_DONTWAIT);
    if (bytes <= 0) 
	{
        return;
    }
	KK_Sendto_CloudData(dat,bytes);
    INFO_PRINT("kk_data_cb:%s \r\n", (char *)dat);
    nn_freemsg(dat);
}

static int kk_nanomsg_init(kk_nanomsg_handle_t *nanoMsgHdl)
{
	if(nanoMsgHdl == NULL)
	{
		return -1;
	}
 	nanoMsgHdl->handle.n = nn_socket(AF_SP, NN_PAIR);	
    if (nanoMsgHdl->handle.n < 0) 
	{
        return -1;
    }	
    if (nn_connect(nanoMsgHdl->handle.n,NANOMSG_ADDR) < 0) 
	{
        return -1;
    }
    size_t size = sizeof(size_t);
    if (nn_getsockopt(nanoMsgHdl->handle.n, NN_SOL_SOCKET, NN_RCVFD, (char *)&nanoMsgHdl->handle.s, &size) < 0) 
	{
        return -1;
    }	
	return 0;
}

struct ev_loop* kk_loop_init(kk_nanomsg_handle_t *nanoMsgHdl)
{
    static struct ev_io watcher_b;
    struct ev_loop *loop = ev_loop_new(EVBACKEND_EPOLL);
    if (NULL == loop) 
	{
        ERROR_PRINT("create loop failed\r\n");
        return NULL;
    }
    ev_io_init (&watcher_b, kk_data_cb, nanoMsgHdl->handle.s, EV_READ);
    ev_io_start (loop, &watcher_b);
    return loop;
}
void KK_Data_Handle(void)
{
	int rc = 0;

	rc = kk_nanomsg_init(&s_msgHdl);
    struct ev_loop* kloop = kk_loop_init(&s_msgHdl);
    if (NULL == kloop) 
	{
        ERROR_PRINT("Bloop init failed\r\n");
        return ;
    }
    ev_set_userdata(kloop, &s_msgHdl);
    ev_run (kloop, 0);
    return ;
}