#include "define.h"
#include "PrintfServer.h"
#ifdef USE_WINC1500  
#else  
#include "TCPIP_Stack/TCPIP.h"
#endif
#include <stdio.h>

//BYTE vTelnetSession;
WORD w, w2;
#ifdef USE_WINC1500  
#else  
TCP_SOCKET MyPrintfSocket;
#endif

char mPrintfString[1024];    //Make shure this string is at least as big as the heap
BOOL mPrintfAvailable;

int OpenPrintfServer()
{
    memset(mPrintfString,'\0',1024);
    
#ifdef USE_WINC1500  
    return 0;
#else  
    MyPrintfSocket = TCPOpen(0, TCP_OPEN_SERVER, 6463, TCP_PURPOSE_GENERIC_TCP_SERVER);

    
    if (MyPrintfSocket == INVALID_SOCKET)
    {
        
        return 0;        
    }
    mPrintfAvailable = FALSE;
    return 1;
#endif
    
}

void TickPrintfServer()
{
    int length;
    static int PrintfServerTickState = PRINTF_SERVER_INIT_STATE;
    
    switch(PrintfServerTickState)
    {
        case PRINTF_SERVER_INIT_STATE:
        {
            if(OpenPrintfServer() == 1)
            {
                PrintfServerTickState = PRINTF_SERVER_RUN_STATE;
            }
            break;
        }
        case PRINTF_SERVER_RUN_STATE:
        {

#ifdef USE_WINC1500  
#else              
            if(TCPIsConnected(MyPrintfSocket) == FALSE)
            {
                mPrintfAvailable = FALSE;
                return;
            }
            else
            {
                if(mPrintfAvailable == FALSE)
                {
                    mPrintfAvailable = TRUE;
                    TCPPutString(MyPrintfSocket,"Sprinkler printf console\n");
                    
                }
            }
            
            
            
            length = (int)strlen(mPrintfString);
            if(length > 0 /*&& TCPIsPutReady(MySocket) > length*/)
            {
                TCPPutString(MyPrintfSocket,mPrintfString);
                memset(mPrintfString,'\0',1024);
            }
#endif
            
            break;
        }
    }
 }

void TelnetPutPrintf(char c)
{
    if(mPrintfAvailable == FALSE)
        return;
    
//    if(strlen(mPrintfString) >= 1000)
//        return;
//    
//    strncat(mPrintfString,&c,1);
#ifdef USE_WINC1500  
#else     
    TCPPut(MyPrintfSocket,c);
#endif
   // TCPFlush(MyPrintfSocket);
}
