/*
*
*/
#include "./include/tcp_if.h"
#include "./include/tcp_port.h"

static tcp_sap_t tcp_sap[TCP_MAX_NUM_OF_SAP];

static void tcp_sap_init(tcp_sap_t *ptr_sap, BYTE index)
{
	if((ptr_sap == NULL) || (index >= TCP_MAX_NUM_OF_SAP))
	{
		return;
	}
	
	ptr_sap->id = index;
	strcpy(ptr_sap->name, "\0");
	ptr_sap->recv_cb = NULL;
}

tcp_sap_t *tcp_sap_get_by_index(int index)
{
	if(index < 0 || index >= TCP_MAX_NUM_OF_SAP)
		return NULL;
	return &tcp_sap[index];
}

void tcp_init(void)
{
	WORD i;

	for(i = 0; i < TCP_MAX_NUM_OF_SAP; i++)
	{
		tcp_sap_init(&tcp_sap[i], (BYTE)i);
	}

	for(i = 0; i < TCP_MAX_NUM_OF_PORT; i++)
	{
		tcp_port_init(i);
	}
	
	return;
}

void tcp_timer(void)
{
	tcp_link_fsm();
	tcp_port_recv_msg();
}

int tcp_bind(tcp_sap_t *ptr_sap)
{
	BYTE i;
	tcp_sap_t *ptr_tmp = NULL;

	if((ptr_sap == NULL) || (ptr_sap->recv_cb == NULL))
	{
		return -1;
	}

	for(i = 0; i < TCP_MAX_NUM_OF_SAP; i++)
	{
		ptr_tmp = &tcp_sap[i];
		if(ptr_tmp->recv_cb != NULL)
		{
			continue;
		}
		
		memcpy((BYTE*)ptr_tmp, ptr_sap, sizeof(tcp_sap_t));
		ptr_tmp->id = i;
		ptr_tmp->name[TCP_MAX_USER_NAME_LEN-1] = '\0';

		return i;
	}

	return -1;
}

int tcp_unbind(tcp_sap_t *ptr_sap, BYTE index)
{
	if((ptr_sap == NULL) || (index >= TCP_MAX_NUM_OF_SAP))
	{
		return -1;
	}
	
	if(ptr_sap->id != index)
	{
		return -1;
	}
	
	tcp_sap_init(ptr_sap, index);

	return 0;
}

