// WetSocket.cpp: implementation of the CWetSocket class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "WetSocket.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CWetSocket::CWetSocket()
{
	connected = false;

}

CWetSocket::~CWetSocket()
{

}

int CWetSocket::OpenConnection(SOCKET_DATA newSock)
{
	unsigned long cmd = 1;
	WORD wVersionRequested;
	WSADATA wsaData;
	int result; 
	wVersionRequested = MAKEWORD( 2, 2 ); 
	result = WSAStartup( wVersionRequested, &wsaData );
	
	if ( result != 0 ) 
	{
		// Tell the user that we could not find a usable 
		// WinSock DLL.                                      
		AfxMessageBox("Could not find a usable Winsock DLL, aborting");
		return 0;
	} 
		// Confirm that the WinSock DLL supports 2.2.
		// Note that if the DLL supports versions greater    
		// than 2.2 in addition to 2.2, it will still return 
		// 2.2 in wVersion since that is the version we      
		// requested.                                         
	if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
	{
		// Tell the user that we could not find a usable 
		// WinSock DLL.                                    
		AfxMessageBox("Could not find a usable Winsock DLL, aborting!");
		WSACleanup( );
		return 0;
	}
	 // The WinSock DLL is acceptable. Proceed. 

	BOOL bReUseAddr = TRUE;			// DESC: Boolean for SetSockOpt. 
	SOCKADDR_IN	aSockAddr;
	BOOL			re_use_addr = TRUE;			  // DESC: Boolean for SetSockOpt.
	SOCKET		sock		= INVALID_SOCKET; //temp soket
 
	aSockAddr.sin_family			 = AF_INET;
	aSockAddr.sin_port			 = htons((unsigned short)newSock.port);
	aSockAddr.sin_addr.S_un.S_addr = htonl((unsigned long)newSock.address);
	
	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  
	//check the status of the socket
	if(sock == INVALID_SOCKET)
	{
	  m_socket  = INVALID_SOCKET;
	  connected = false;
	  return 2;
	 }
	//socket is valid so now set options
	 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&re_use_addr, sizeof(int)) == SOCKET_ERROR)
	 {
		m_socket  = INVALID_SOCKET;
		connected = false;
		return 3;
	}	
	//options set ok, now connect
	if( connect(sock, (sockaddr *)&aSockAddr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
	{
		m_socket  = INVALID_SOCKET;
		connected = false;
		return 4;
	}
	//everything ok, now assign class socket var mySocket 
	m_socket = sock;
	connected = true;
	return 1;
}

bool CWetSocket::CloseConnection()
{
	if(m_socket != INVALID_SOCKET){
		closesocket(m_socket);
		connected = false;
		return true;
	}
	else
		return false;
}
