#include "tfe_utils.h"
#include "tfe_types.h"
#include "tfe_cmsg.h"
#include "MESA/MESA_prof_load.h"
#include <sys/socket.h>
#include <unistd.h>
#include <event2/util.h>

struct sender_scm
{
	int sockfd;
	struct sockaddr_in server_addr;
	int send_switch;
	void *logger;
};

void send_scm_destroy(struct sender_scm *sender)
{
	if(sender != NULL)
	{
		if(sender->sockfd >= 0)
		{
			close(sender->sockfd);
		}
	}
	FREE(&sender);
}


/* TODO:
0: switch
1. no_blocking + eagain
2. libevent
3. field_stat: success/failed
*/
struct sender_scm* sender_scm_init(const char *profile, const char *section, void *logger)
{
	char kni_ip[INET_ADDRSTRLEN] = "";
	int send_switch = -1;
	int kni_port = -1;
	int sockfd = -1;
	struct sockaddr_in server_addr;
	struct sender_scm *sender = ALLOC(struct sender_scm, 1);
	sender->logger = logger;
	MESA_load_profile_int_def(profile, section, "send_switch", &send_switch, 1);
	if(send_switch)
	{
		MESA_load_profile_string_def(profile, section, "ip", kni_ip, sizeof(kni_ip), "127.0.0.1");
		MESA_load_profile_int_def(profile, section, "cmsg_port", &kni_port, 2475);
		TFE_LOG_INFO(logger, "MESA_prof_load, [%s]:\n kni_ip: %s\n kni_port: %d",
						section, kni_ip, kni_port);
	}
	sender->send_switch = send_switch;
	if(send_switch == 0)
	{
		return sender;
	}
	//create socket
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0)
	{
		TFE_LOG_ERROR(logger, "Failed at create udp socket, errno is %d, %s", errno, strerror(errno));
		/* after log, reset errno */
		errno = 0;
		goto error_out;
	}

	evutil_make_socket_nonblocking(sockfd);

	sender->sockfd = sockfd;
	//server_addr
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(kni_port);
    server_addr.sin_addr.s_addr = inet_addr(kni_ip);
	sender->server_addr = server_addr;
	return sender;

error_out:
	send_scm_destroy(sender);
	return NULL;
}

int sender_scm_cmsg_send(struct sender_scm *sender, struct tfe_cmsg *cmsg)
{
	void *logger = sender->logger;
	int send_switch = sender->send_switch;
	if(send_switch == 0)
	{
		return 0;
	}
	uint16_t bufflen = tfe_cmsg_serialize_size_get(cmsg);
	unsigned char *buff = ALLOC(unsigned char, bufflen);
	uint16_t serialize_len = 0;
	int ret = tfe_cmsg_serialize(cmsg, buff, bufflen, &serialize_len);
	if(ret < 0)
	{
		TFE_LOG_ERROR(logger, "Failed at serialize tfe cmsg, ret is %d", ret);
		goto error_out;
	}
	ret = sendto(sender->sockfd, buff, serialize_len, MSG_CONFIRM,
		(struct sockaddr *)&(sender->server_addr), sizeof(sender->server_addr));
	if(ret < 0)
	{
		TFE_LOG_ERROR(logger, "Failed at send udp data, errno is %d, %s", errno, strerror(errno));
		/* after log, reset errno */
		errno = 0;
		goto error_out;
	}	
	FREE(&buff);
	return 0;

error_out:
	FREE(&buff);
	return -1;
}


