#include "predef.h"
#include <stdio.h>
#include <ctype.h>
#include <startnet.h>
#include <autoupdate.h>
#include <dhcpclient.h>
#include <smarttrap.h>
#include <taskmon.h>
#include <NetworkDebug.h>

#include <constants.h>
#include <tcp.h>
#include "bsp.h"

#include <string.h>

extern "C" {
void UserMain(void * pd);
}

const char * AppName="BulkTCPTest";


void testNBSocket()
{
	int socket = ::connect (AsciiToIp("131.198.207.160"), 0, 22222, 20);
	
	iprintf("Socket: %d\n", socket);
	
	if(socket < 0)
	{
		iprintf("Connection error... exiting routine.\n");
		return;
	}
	
   const int buffer_size = 10000; /// Change this variable to 6000 or less and everything works fine
   char buffer[buffer_size];

   const char T = 'T'; /// T is for Test
   memset(buffer, T, buffer_size);
   buffer[buffer_size-1] = '\0';
   
   iprintf("Sending message...\n");
   
   ::write (socket, (char*)buffer, buffer_size);

   int bytes_received = ::ReadWithTimeout(socket, (char*)buffer, buffer_size, 5*TICKS_PER_SECOND);
   
   if(bytes_received <= 0)
   {
      iprintf("Receive error: %d\n", bytes_received);
   }
   else
   {
   	iprintf("Received %d\n", bytes_received);
   	iprintf("%s\n", buffer);
   }
   
   close(socket);
}

void UserMain(void * pd) 
{
    InitializeStack();
    if (EthernetIP == 0) GetDHCPAddress();
    OSChangePrio(MAIN_PRIO);
    EnableAutoUpdate();
    //StartHTTP();
    //EnableTaskMonitor();

    #ifndef _DEBUG
    EnableSmartTraps();
    #endif

    #ifdef _DEBUG
    InitializeNetworkGDB_and_Wait();
    #endif

    iprintf("Application started\n");
    while (1) 
    {
	     iprintf("Choose an option...\n");
	     iprintf("x - Exit and reboot\n");
	     iprintf("0 - Sleep (5 sec)\n");
	     iprintf("1 - Test NB socket\n");
	
	     char tmp;
	     iscanf("%s", &tmp);
	     
	     
	     switch(tmp)
	     {
	     case 'x':
	     {
	     		ForceReboot();
	     		break;
	     }
	     case '0':
	     {
	     	   iprintf ("Sleeping...\n");
	     	   OSTimeDly(200);
	     	   break;
	     }
	     case '1':
	     {
	     		testNBSocket();
	     		break;
	     }
	     
	     default:
	     {
	     	iprintf("Invalid entry\n");
	     		break;
	     }
	    }
    }
}
