// RequestSocket.cpp : implementation file
//

#include "stdafx.h"
#include "BaseClient.h"
#include "RequestSocket.h"
#include "BaseClientDlg.h"

// CRequestSocket

CRequestSocket::CRequestSocket(CBaseClientDlg *pDlg)
{
	m_buf.SetSize( 1024 );
	m_nRefs = 1;
	m_pDlg = pDlg;
}

CRequestSocket::~CRequestSocket()
{
}


// CRequestSocket Member functions

void CRequestSocket::OnReceive(int nErrorCode)
{
	int ndx = 0;
// get the data....
	int nBytes = Receive( m_buf.GetData(), (int)m_buf.GetSize() );
	if ( nBytes != SOCKET_ERROR )
	{
		while( ndx < nBytes )
		{
			// for Debugging (Set a break point here to see the message string)
			char ch = (char)(m_buf.GetAt( ndx ));
			++ndx;
		}
		nBytes = Send( m_buf.GetData(), ndx);
		if ( nBytes == SOCKET_ERROR )
		{
			if ( GetLastError() != WSAEWOULDBLOCK )
			{
				Release();
			} else {
				BOOL bOk = AsyncSelect( FD_WRITE | FD_CLOSE );
				ASSERT(bOk);
			}
		}
	} else {
		nBytes = GetLastError(); // Ignore error
	}
	ProcessCommand(&m_buf, ndx);
}

void CRequestSocket::OnSend(int nErrorCode)
{
	CAsyncSocket::OnSend(nErrorCode);
}

void CRequestSocket::OnClose(int nErrorCode)
{
	CAsyncSocket::OnClose(nErrorCode);
	Release();
}

int CRequestSocket::AddRef( void )
{
	return ++m_nRefs;
}

int CRequestSocket::Release( void )
{
	int nRefs = --m_nRefs;
	if ( nRefs == 0 )
		delete this;
	return nRefs;
}
void CRequestSocket::ProcessCommand(CByteArray* pbuf, int nBufLen)
{
	// Check the first character that comes from the Socket
	// Modify CBaseClientDlg::OnBtnPlay() to perform the motion.
	switch (pbuf->GetAt(0))
	{
		case '1' : m_pDlg->m_iRadio1 = 0; break;
		case '2' : m_pDlg->m_iRadio1 = 1; break;
		case '3' : m_pDlg->m_iRadio1 = 2; break;
		default : m_pDlg->m_iRadio1 = -1;
	}
	m_pDlg->UpdateData(FALSE);
	m_pDlg->OnBtnPlay();
}