#include "selfcare_udp.h"
#include "selfcare_config.h"
#include "selfcare_proxy.h"
#include "rest_proxy.h"
#include "log.h"


/* 本地监听udp端口 */
static int g_udp_listfd;
/* 线程运行标记 */
static int g_udp_runflag;
/* 收到udp消息回调 */
static selfcare_udp_handle_s g_udp_handle;

extern int init_socket(unsigned int local_addr, short local_port, char stype, int noblock_flag);

static int _selfcare_udp_initfd(const unsigned int local_addr, const short local_port)
{
	int fd;

	fd = init_socket(local_addr, local_port, 0, 1);
	if(fd <= 0)
	{
		LOG_E("[selfcare] init udp fd err. IPPort[%u:%d]\n", local_addr, local_port);
		exit(-1);
	}
	
	return fd;
}
static void *_selfcare_udp_thread(void *data)
{
	prctl(PR_SET_NAME, "selfcare-udpserver");

	char buf[MAX_BUFFER];
	int len;
	int ip;
	short port;

    while(g_udp_runflag)
    {
		len = udp_recv_with_ip_info(g_udp_listfd, buf, MAX_BUFFER, &ip, &port);
		if(len > 0)
		{
			g_udp_handle.handle(buf, len);
		}

		usleep(10);
    }
    pthread_exit(NULL);

	return NULL;
}

void _selfcare_udp_process()
{
	char buf[MAX_BUFFER];
	int len;
	int ip;
	short port;

    {
		len = udp_recv_with_ip_info(g_udp_listfd, buf, MAX_BUFFER, &ip, &port);
		if(len > 0)
		{
			g_udp_handle.handle(buf, len);
		}

    }

}


static int _selfcare_udp_inittask()
{
    pthread_t handle;
	g_udp_runflag = 1;
    if(pthread_create(&handle, NULL, _selfcare_udp_thread, NULL))
    {
        printf("Thread create err !!!\n");
		return FAILURE;
		
        if ( pthread_detach(handle) )
        {
            printf("Thread detached err !!!\n");
			return FAILURE;
        }
    }
	return SUCCESS;
}

int selfcare_udp_init(void)
{
	/* 初始化本地监听udp端口 */
	g_udp_listfd = _selfcare_udp_initfd(selfcare_config_get()->udp_local_ip, selfcare_config_get()->udp_local_port);

	int ret=SUCCESS;
	//ret = _selfcare_udp_inittask();
	if(ret != SUCCESS)
	{
		return ret;
	}
	
	return SUCCESS;
}

void selfcare_udp_uninit(void)
{
	g_udp_runflag = 0;
}

int selfcare_udp_reg(selfcare_udp_handle_s *handle)
{
	memcpy(&g_udp_handle, handle, sizeof(selfcare_udp_handle_s));
	
	return SUCCESS;
}

int selfcare_udp_send(char *buf, short len)
{
	return udp_send(g_udp_listfd, selfcare_config_get()->udp_ocs_ip, selfcare_config_get()->udp_ocs_port, buf, len);
}

