
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <memory.h> 
#include <errno.h>

#include <stdio.h>

#include "typedef.h"

#include "cSocketM.h"

#include "LogMsg.h"

cSocketM::cSocketM()
{
}

bool cSocketM::Create(void)
{
    m_Sck = socket(AF_INET, SOCK_STREAM, 0);

    LogMsg( LOGLEVEL_SOCKET,"cSocketM::Create %d\n",m_Sck);

    if(m_Sck == -1)
        return(0);
    else
        return(1);
}

void cSocketM::Close(void)
{
    LogMsg( LOGLEVEL_SOCKET,"cSocketM::Close\n");
//    close(m_Sck);
}

bool cSocketM::Connect(const char *lpszHostAddress,unsigned int nHostPort)
{
    int ret;
    struct sockaddr_in  srv;
    struct hostent *half;

    LogMsg( LOGLEVEL_SOCKET,"cSocketM::Connect : %s:%d\n",lpszHostAddress,nHostPort);

    memset(&srv,'\0',sizeof(srv));

    srv.sin_addr.s_addr = inet_addr( lpszHostAddress );

    if( srv.sin_addr.s_addr < 0)
    {
        half = gethostbyname( lpszHostAddress );

        if(half != NULL)
        {
            memcpy( &srv.sin_addr.s_addr, (half->h_addr), 4 );
            srv.sin_family = half->h_addrtype; 
        }
    }
    
    srv.sin_family = AF_INET;
    srv.sin_port = htons((u_short)nHostPort);

    ret = connect( m_Sck, (struct sockaddr *)&srv, sizeof( struct sockaddr_in ));

    return( !ret );
}

//bool cSocketM::Connect(string lpszHostAddress,unsigned int nHostPort)
//{
//  return( Connect((char *)lpszHostAddress.cstr(),nHostPort) );
//}
//

int cSocketM::Send(const void* lpBuf,int nBufLen,int nFlags /*=0*/)
{

	LogMsg( LOGLEVEL_SOCKET,"cSocketM::Send %d\n",nBufLen);
 //   LogMsg( LOGLEVEL_SOCKET_DATA,"cSocketM::Send %d :'%s'\n",nBufLen,lpBuf);
	for(int i=0;i<nBufLen;i++)
		LogMsg( LOGLEVEL_SOCKET_DATA,"%02x ",((char*)(lpBuf))[i]);
	LogMsg( LOGLEVEL_SOCKET_DATA,"\n");

    return( send ( m_Sck, (const char*)lpBuf , nBufLen, nFlags ) );
}

int cSocketM::Receive(void* lpBuf,int nBufLen,int nFlags /*=0*/)
{
//	char *ptrc;
	int ret = 0;
    
	LogMsg( LOGLEVEL_SOCKET,"cSocketM::Receive\n");

	ret = recv ( m_Sck, (char*)lpBuf, nBufLen, nFlags );

//	if(ret>0)
//	{
//		ptrc = (char*)lpBuf;	ptrc+=ret;	*ptrc=0;
//	}
	LogMsg( LOGLEVEL_SOCKET_DATA,"cSocketM::Receive %d/%d\n",ret,nBufLen);
//	LogMsg( LOGLEVEL_SOCKET_DATA,"cSocketM::Receive %d/%d : '%s'\n",ret,nBufLen,lpBuf);

    return( ret );
}


int cSocketM::WaitReceive()
{
	int n = 0;
	struct timeval tv;

    fd_set read_fds;

    FD_ZERO(&read_fds);
    FD_SET( m_Sck, &read_fds );

	tv.tv_sec = 5;
	tv.tv_usec = 0;

	while( n == 0 )
	{
		n = select( 1, &read_fds, NULL, NULL, &tv);
		LogMsg( LOGLEVEL_SOCKET,"cSocketM::select return %d\n",n);
		if(n == -1)
			LogMsg( LOGLEVEL_SOCKET,"cSocketM::select error ! n°%d\n",errno);
			
	}
 
    FD_ZERO(&read_fds);

    return(1);
}
