#ifndef __MWEBSOCKET_H__
#define __MWEBSOCKET_H__
#include "msystem.h"

#define WS_DATATYPE_MINDATA 0x80  // 0x0：中间数据包
#define WS_DATATYPE_TXTDATA 0x81  // 0x1：txt类型数据包
#define WS_DATATYPE_BINDATA 0x82  // 0x2：bin类型数据包
#define WS_DATATYPE_DISCONN 0x88  // 0x8：断开连接类型数据包 收到后需手动 close(fd)
#define WS_DATATYPE_PING    0x89  // 0x9：ping类型数据包, 自动回复pong
#define WS_DATATYPE_PONG    0x8A  // 0xA：pong类型数据包

typedef struct mwebsocket
{
    int fd;
    int debug;
    int connected;
    int handshaked;
    struct sockaddr_in selfaddr;
    struct sockaddr_in peeraddr;
    char self_ip[128];
    short self_port;
    short peer_port;
    char peer_ip[128];

    short server_port;
    char path[128];
    char server_ip[64];
    char Sec_WebSocket_Key[128];
    char Sec_WebSocket_Accept[128];
    char Sec_WebSocket_Protocol[128];

    uint8_t txbuff[4096];
    uint8_t rxbuff[4096];
    uint8_t txstream[4096+32];
    uint8_t rxstream[4096+32];

    int txbyte;
    int rxbyte;

    uint8_t txtype;
    uint8_t txmask;

    uint8_t rxtype;
    uint8_t rxmask;

    void* priv;
    int (*on_recv_callback)(void* priv, uint8_t* data, int length, uint8_t type);
}mwebsocket_t;

//client
int mwebsocket_client_connect(mwebsocket_t* dev, const char* server_ip, short server_port);
int mwebsocket_client_handshake(mwebsocket_t* dev);

//server
int mwebsocket_server_listen(mwebsocket_t* dev, const char* ifname, short server_port);
int mwebsocket_server_handshake(mwebsocket_t* dev);

//common
void mwebsocket_init(mwebsocket_t* dev, int fd, const char* self_ip, short self_port, const char* peer_ip, short peer_port);
void mwebsocket_exit(mwebsocket_t* dev);

int mwebsocket_create(mwebsocket_t* dev);
int mwebsocket_block(mwebsocket_t* dev);
int mwebsocket_unblock(mwebsocket_t* dev);
int mwebsocket_bind(mwebsocket_t* dev, const char* self_ip, short self_port);
int mwebsocket_listen(mwebsocket_t* dev, int max_connectors);
int mwebsocket_accept(mwebsocket_t* dev, mwebsocket_t* new);
int mwebsocket_connect(mwebsocket_t* dev, const char* peer_ip, short peer_port);

int mwebsocket_send(mwebsocket_t* dev);
int mwebsocket_recv(mwebsocket_t* dev);
int mwebsocket_recv_timeout(mwebsocket_t* dev, int timeout);

#endif//__MWEBSOCKET_H__
