#ifndef __MW_TCPCLIENT_H__
#define __MW_TCPCLIENT_H__
#include <stdint.h>
#include "list.h"
#include "kpacket.h"
#include "json_packet.h"
#include "hloop.h"
#include "hbase.h"
#include "hthread.h"



typedef enum{
	CONN_STARTED = 1,       //1 thread start(note:network ok[connected to AP] to trigger it), opposite DESTROY
	CONN_CONNECTING,        //2
    CONN_CONNECTED,         //3
    CONN_SECOND_TICK,       //4 event to up level
    CONN_CLOSED,			//5
    CONN_DESTROY,           //6 thread end
    CONN_RESERVED
}ConnEvent;


typedef struct tcpclient tcpclient;

typedef struct{
    int32_t     (*on_packet)(tcpclient *client, void *data);  /* 回调 TLV*/
	int32_t     (*on_unpacket)(tcpclient *client, iobuffer *iobuf);   /*in: 收到数据进行解包*/
	int32_t     (*on_pack)(char *out_data, const uint32_t max_sz, const char *in_data, const uint32_t sz);	/*out:以特定格式打包后以备发出, 与on_unpacket相反*/
}packet_handler;

typedef struct tcpclient{
	int8_t  	 	 status;// 'I' idle(initial), 'R' running, 'E' exit
	hloop_t          *loop;
	int16_t 	 	 stack_size;
    iobuffer 		 read_iobuf;
	hthread_t 	     th;
	packet_handler   handler;
    hio_t            *hio; /*连接的hio, 如果多个则自动选择, 最快那个*/
}tcpclient;


tcpclient *tcpclient_init(int stack_size, packet_handler handler);

/**
 * 支持多个连接同时发起， 最快连接上的会close掉后面连接的
**/
void tcpclient_conn(tcpclient *tclient, const char* domain_or_ip, int port);
int32_t tcpclient_send(tcpclient *tclient, const char *data, const uint32_t sz);
int32_t tcpclient_deinit(tcpclient *tclient);


void tcpclient_test();


#endif /* __MW_TCPCLIENT_H__ */
