#include "lwip/debug.h"
#include "lwip/stats.h"
#include "lwip/tcp.h"
#include "stm32f10x.h"
#include "netconf.h"
#include "stm32_config.h"

#define TS_RECVBUFF  200

static u8  TcpServer_buff[TS_RECVBUFF]="";
static u32 TcpServer_len = 0;

#if LWIP_TCP

static struct tcp_pcb *tcp_echoserver_pcb;
struct tcp_pcb *Socket_Server;
//static u16_t TcpClientPort = 0;
/* ECHO protocol states */
enum tcp_echoserver_states {
	ES_NONE = 0,
	ES_ACCEPTED,
	ES_RECEIVED,
	ES_CLOSING
};

/* structure for maintaing connection infos to be passed as argument 
   to LwIP callbacks*/
struct tcp_echoserver_struct {
	u8_t state;             /* current connection state */
	struct tcp_pcb *pcb;    /* pointer on the current tcp_pcb */
	struct pbuf *p;         /* pointer on the received/to be transmitted pbuf */
};

static err_t tcp_echoserver_accept(void *arg, struct tcp_pcb *newpcb, err_t err);
static err_t tcp_echoserver_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err);
static void tcp_echoserver_error(void *arg, err_t err);
static err_t tcp_echoserver_poll(void *arg, struct tcp_pcb *tpcb);
static err_t tcp_echoserver_sent(void *arg, struct tcp_pcb *tpcb, u16_t len);
static void tcp_echoserver_send(struct tcp_pcb *tpcb, struct tcp_echoserver_struct *es);
static void tcp_echoserver_connection_close(struct tcp_pcb *tpcb, struct tcp_echoserver_struct *es);


/**
  * @brief  Initializes the tcp echo server
  * @param  None
  * @retval None
  */
void tcp_echoserver_init(void)
{
	/* create new tcp pcb */
	tcp_echoserver_pcb = tcp_new();
	if (tcp_echoserver_pcb != NULL)
	{
		err_t err;
		err = tcp_bind(tcp_echoserver_pcb, IP_ADDR_ANY, 8081);
		if (err == ERR_OK)
		{
			/* start tcp listening for echo_pcb */
			//tcp_echoserver_pcb = tcp_listen(tcp_echoserver_pcb);
			//ÉèÖÃ¼àÌýÊýÄ¿ÎªTCP_LISTEN_BACKLOG = 1
			tcp_echoserver_pcb = tcp_listen_with_backlog(tcp_echoserver_pcb, TCP_LISTEN_BACKLOG);
			/* initialize LwIP tcp_accept callback function */
			tcp_accept(tcp_echoserver_pcb, tcp_echoserver_accept);
		}
	}
}

/**
  * @brief  This function is the implementation of tcp_accept LwIP callback
  * @param  arg: not used
  * @param  newpcb: pointer on tcp_pcb struct for the newly created tcp connection
  * @param  err: not used 
  * @retval err_t: error status
  */
static err_t tcp_echoserver_accept(void *arg, struct tcp_pcb *newpcb, err_t err)
{
	err_t ret_err;
	struct tcp_echoserver_struct *es;
	DEBUG();
	LWIP_UNUSED_ARG(arg);
	LWIP_UNUSED_ARG(err);
	/* set priority for the newly accepted tcp connection newpcb */
	tcp_setprio(newpcb, TCP_PRIO_MIN);
	/* allocate structure es to maintain tcp connection informations */
	es = (struct tcp_echoserver_struct *)mem_malloc(sizeof(struct tcp_echoserver_struct));
	DEBUG();
	if (es != NULL)
	{
		DEBUG();
		es->state = ES_ACCEPTED;
		es->pcb = newpcb;
		es->p = NULL;
		tcp_arg(newpcb, es);                      /* pass newly allocated es structure as argument to newpcb */
		tcp_recv(newpcb, tcp_echoserver_recv);    /* initialize lwip tcp_recv callback function for newpcb  */ 
		tcp_err(newpcb, tcp_echoserver_error);    /* initialize lwip tcp_err callback function for newpcb  */
		tcp_poll(newpcb, tcp_echoserver_poll, 1); /* initialize lwip tcp_poll callback function for newpcb */
		Socket_Server = newpcb;
		ret_err = ERR_OK;
	}
	else
	{
		ret_err = ERR_MEM;/* return memory error */
	}
	return ret_err;  
}


/**
  * @brief  This function is the implementation for tcp_recv LwIP callback
  * @param  arg: pointer on a argument for the tcp_pcb connection
  * @param  tpcb: pointer on the tcp_pcb connection
  * @param  pbuf: pointer on the received pbuf
  * @param  err: error information regarding the reveived pbuf
  * @retval err_t: error code
  */
static err_t tcp_echoserver_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
{
	uint8_t *Data;
	int i = 0;
	struct tcp_echoserver_struct *es;
	err_t ret_err;
	LWIP_ASSERT("arg != NULL",arg != NULL);
	es = (struct tcp_echoserver_struct *)arg;
	/* if we receive an empty tcp frame from client => close connection */
	if (p == NULL)
	{
		DEBUG();
		/* remote host closed connection */
		es->state = ES_CLOSING;
		if(es->p == NULL)
		{
			DEBUG();
			/* we're done sending, close connection */
			tcp_echoserver_connection_close(tpcb, es);
		}
		else
		{
			DEBUG();
			/* we're not done yet */
			/* acknowledge received packet */
			tcp_sent(tpcb, tcp_echoserver_sent);
			/* send remaining data*/
			tcp_echoserver_send(tpcb, es);
		}
		ret_err = ERR_OK;
	}   
	/* else : a non empty frame was received from client but for some reason err != ERR_OK */
	else if(err != ERR_OK)
	{
		DEBUG();
		/* free received pbuf*/
		if (p != NULL)
		{
			es->p = NULL;
			pbuf_free(p);
		}
		ret_err = err;
		DEBUG();
	}
	else if (es->state == ES_RECEIVED || es->state == ES_ACCEPTED)
	{
		es->state = ES_RECEIVED;
		/* more data received from client and previous data has been already sent*/
		if(es->p == NULL)
		{
			es->p = p;
			if(!TcpServer_len)
			{
				TcpServer_len = p->tot_len;
				Data = (uint8_t*)p->payload;
				for(i = 0;(i<TS_RECVBUFF-1) && (i < TcpServer_len) ;i++)
				{
					TcpServer_buff[i] = Data[i];
				}		
				TcpServer_buff[i] = '\0';
			}
			tcp_echoserver_send(tpcb, es);
		}
		else
		{
			struct pbuf *ptr;
			/* chain pbufs to the end of what we recv'ed previously  */
			ptr = es->p;
			pbuf_chain(ptr,p);
			DEBUG();
		}
		ret_err = ERR_OK;
	}

	/* data received when connection already closed */
	else
	{
		DEBUG();
		/* Acknowledge data reception */
		tcp_recved(tpcb, p->tot_len);
		DEBUG();
		/* free pbuf and do nothing */
		es->p = NULL;
		pbuf_free(p);
		ret_err = ERR_OK;
	}
	return ret_err;
}

/**
  * @brief  This function implements the tcp_err callback function (called
  *         when a fatal tcp_connection error occurs. 
  * @param  arg: pointer on argument parameter 
  * @param  err: not used
  * @retval None
  */
static void tcp_echoserver_error(void *arg, err_t err)
{
	struct tcp_echoserver_struct *es;
	LWIP_UNUSED_ARG(err);
	es = (struct tcp_echoserver_struct *)arg;
	if (es != NULL)
	{
		Socket_Server->state = CLOSE_WAIT;
		tcp_echoserver_connection_close(Socket_Server, es);
		mem_free(es);
	}
}

/**
  * @brief  This function implements the tcp_poll LwIP callback function
  * @param  arg: pointer on argument passed to callback
  * @param  tpcb: pointer on the tcp_pcb for the current tcp connection
  * @retval err_t: error code
  */
static err_t tcp_echoserver_poll(void *arg, struct tcp_pcb *tpcb)
{
	err_t ret_err;
	struct tcp_echoserver_struct *es;
	DEBUG();
	es = (struct tcp_echoserver_struct *)arg;
	if (es != NULL)
	{
		if (es->p != NULL)
		{
			/* there is a remaining pbuf (chain) , try to send data */
			tcp_echoserver_send(tpcb, es);
		}
		else
		{
			/* no remaining pbuf (chain)  */
			if(es->state == ES_CLOSING)
			{
				/*  close tcp connection */
				tcp_echoserver_connection_close(tpcb, es);
			}
		}
		ret_err = ERR_OK;
	}
	else
	{
		/* nothing to be done */
		tcp_abort(tpcb);
		ret_err = ERR_ABRT;
	}
	return ret_err;
}

/**
  * @brief  This function implements the tcp_sent LwIP callback (called when ACK
  *         is received from remote host for sent data) 
  * @param  None
  * @retval None
  */
static err_t tcp_echoserver_sent(void *arg, struct tcp_pcb *tpcb, u16_t len)
{
	struct tcp_echoserver_struct *es;
	LWIP_UNUSED_ARG(len);
	es = (struct tcp_echoserver_struct *)arg;
	if(es->p != NULL)
	{
		/* still got pbufs to send */
		tcp_echoserver_send(tpcb, es);
	}
	else
	{
		/* if no more data to send and client closed connection*/
		if(es->state == ES_CLOSING)
			tcp_echoserver_connection_close(tpcb, es);
	}
	return ERR_OK;
}


/**
  * @brief  This function is used to send data for tcp connection
  * @param  tpcb: pointer on the tcp_pcb connection
  * @param  es: pointer on echo_state structure
  * @retval None
  */
static void tcp_echoserver_send(struct tcp_pcb *tpcb, struct tcp_echoserver_struct *es)
{
	struct pbuf *ptr;
	u16_t plen;
	err_t wr_err = ERR_OK;
	while ((wr_err == ERR_OK) && (es->p != NULL) && (es->p->len <= tcp_sndbuf(tpcb)))
	{
		ptr = es->p;
		plen = ptr->len;
		es->p = ptr->next;
		if(es->p != NULL)
		{
			pbuf_ref(es->p);
		}
		pbuf_free(ptr);
		tcp_recved(tpcb, plen);
	}
}

/**
  * @brief  This functions closes the tcp connection
  * @param  tcp_pcb: pointer on the tcp connection
  * @param  es: pointer on echo_state structure
  * @retval None
  */
static void tcp_echoserver_connection_close(struct tcp_pcb *tpcb, struct tcp_echoserver_struct *es)
{
	/* remove all callbacks */
	tcp_arg(tpcb, NULL);
	tcp_sent(tpcb, NULL);
	tcp_recv(tpcb, NULL);
	tcp_err(tpcb, NULL);
	tcp_poll(tpcb, NULL, 0);
	/* delete es structure */
	if (es != NULL)
	{
		mem_free(es);
	}  
	/* close tcp connection */
	tcp_close(tpcb);
}

u32 TCP_Server_Recv(u8 *pOut, u32 len)
{
	u32 ret = 0;
	u32 i = 0;
	if(TcpServer_len)
	{
		for(i = 0;(i<TcpServer_len) && (i< len);i++)
		{
			pOut[i] = TcpServer_buff[i];
		}
		pOut[i] = '\0';	 
	}
	ret = TcpServer_len;
	TcpServer_len = 0;
	return ret;
}

s8 TCP_Server_Send(u8 *data, u32 len)
{
	s8 ret = -1;
	err_t wr_err = ERR_OK;
	wr_err = tcp_write(Socket_Server, (char*)data, len, 1);
	if (wr_err == ERR_OK) ret = 0;
	tcp_output(Socket_Server); 
	return ret;
}

#endif /* LWIP_TCP */




