/*
 * CTI_Network_Manager.c
 *
 *  Created on: Apr 9, 2015
 *      Author: user
 */

#include <stdint.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "CTI_Network_manager.h"

//*****************External Application references.**************************************//

extern uint32_t g_ui32SysClock;
struct ip_addr udpDestIpAddr;


//*****************************************************************************
//
// Required by lwIP library to support any host-related timer functions.
//
//*****************************************************************************
/*
void lwIPHostTimerHandler(void)
{

}
*/

int CTI_Network_Init(char *IPAddress,char *Netmask,char *GatewayIP)
{

	uint8_t pui8MACArray[8];
	uint32_t sourceaddr, netmask,gateway;

	UARTprintf("Initializing Network device ....");

    pui8MACArray[0] = 0x01;
    pui8MACArray[1] = 0x02;
    pui8MACArray[2] = 0x03;
    pui8MACArray[3] = 0x01;
    pui8MACArray[4] = 0x02;
    pui8MACArray[5] = 0x03;


	//Initialze the lwIP library, using DHCP.
	sourceaddr=inet_addr(IPAddress);
	netmask=inet_addr(Netmask);
	gateway=inet_addr(GatewayIP);

	/*MAP_IntPrioritySet(INT_EMAC0, ETHERNET_INT_PRIORITY);
	MAP_IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRIORITY);*/


    lwIPInit(g_ui32SysClock,pui8MACArray,sourceaddr,netmask,gateway,IPADDR_USE_STATIC);

    //LocatorInit();
    //LocatorMACAddrSet(pui8MACArray);


    UARTprintf(" Done.\n");
    return 0;

}


struct udp_pcb * CTI_Network_udp_init(int Port)
{
    struct udp_pcb *socketfd = NULL;
    socketfd = udp_new();

    UARTprintf("Initializing UDP ...\n");

    if (socketfd == NULL)
    {
    	UARTprintf(" FAILED.\n");
    	return NULL;
    }

    if (udp_bind(socketfd, IP_ADDR_ANY, Port) != ERR_OK)
    {
    	UARTprintf(" FAILED.\n");
    	return NULL;
    }

	UARTprintf(" Done.\n");

	return socketfd;

}

void CTI_Network_SetTargetIP(int a,int b,int c,int d)
{
	IP4_ADDR(&udpDestIpAddr,a,b,c,d);
}

int CTI_Network_Send(struct udp_pcb *socketfd,unsigned char Data,int Len)
{
	struct pbuf* pbuf1 = NULL;
	pbuf1 = pbuf_alloc(PBUF_TRANSPORT, 100, PBUF_RAM);

	if(pbuf1 != NULL)
	{
		pbuf1->payload = (void*)&Data;

		pbuf1->tot_len = Len;

		pbuf1->len = Len;

		IP4_ADDR(&udpDestIpAddr,172,17,2,30);

		udp_sendto(socketfd, pbuf1,&udpDestIpAddr,1001);

		pbuf_free(pbuf1);

		pbuf1 = NULL;
	}

	return(0);
}

int CTI_Network_Recv(struct udp_pcb *socketfd,unsigned char *Data,int Len)
{
	return(0);
}

int CTI_Network_Close(struct udp_pcb *socketfd)
{
	return(0);
}

