// TCPServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TCPServer.h"
#include "TCPServerDlg.h"
#include "HexDumpData.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CTCPServerDlg dialog

CTCPServerDlg::CTCPServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTCPServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTCPServerDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_Connected = false;
	m_PendingConnection = false;
}

void CTCPServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTCPServerDlg)
	DDX_Control(pDX, IDC_OUTPUT, m_OutputCtrl);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTCPServerDlg, CDialog)
	//{{AFX_MSG_MAP(CTCPServerDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP

	// MySocket massage map functions
	// See "INFO: Use ON_MESSAGE() Macro to Map Less-Common Messages" in MSDN
	// for more information on processing user defined messages
	ON_MESSAGE(WM_MYSOCKET_ONACCEPT, OnMySocketAccept)
	ON_MESSAGE(WM_MYSOCKET_ONRECEIVE, OnMySocketReceive)
	ON_MESSAGE(WM_MYSOCKET_ONCLOSE, OnMySocketClose)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPServerDlg message handlers

BOOL CTCPServerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	m_OutputCtrl.SetFont(CFont::FromHandle((HFONT)GetStockObject(OEM_FIXED_FONT)));

	m_OutputCtrl.AddString(_T("Start"));

	m_ListenSocket.m_Hwnd = m_hWnd;
	m_ConnectedSocket.m_Hwnd = m_hWnd;

	m_OutputCtrl.AddString(_T("Creating socket ..."));
	m_ListenSocket.Create(9101,SOCK_STREAM,FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,"192.168.3.76");

	CString LocalAddress;
	UINT LocalPort = 0;
	m_ListenSocket.GetSockName(LocalAddress, LocalPort);

	CString Message;
	Message.Format(_T("Socket created on %s:%u"), LocalAddress, LocalPort);
	m_OutputCtrl.AddString((LPCTSTR)Message);

	m_OutputCtrl.AddString(_T("Listening ..."));
	m_ListenSocket.Listen(1);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTCPServerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTCPServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

LRESULT CTCPServerDlg::OnMySocketAccept(WPARAM wParam, LPARAM lParam)
{
	if (!m_Connected)
	{
		m_OutputCtrl.AddString(_T("Accepting ..."));

		m_ListenSocket.Accept(m_ConnectedSocket);
		m_Connected = true;

		CString PeerAddress;
		UINT PeerPort = 0;
		m_ConnectedSocket.GetPeerName(PeerAddress, PeerPort);

		CString Message;
		Message.Format(_T("Connected to %s:%u"), PeerAddress, PeerPort);

		m_OutputCtrl.AddString((LPCTSTR)Message);

		BYTE Data[] =
		{
			0x1b, '$',
			'H', 'e', 'l', 'l', 'o', ' ',
			'W', 'o', 'r', 'l', 'd'
		};
		DWORD Length = sizeof(Data);

		m_OutputCtrl.AddString(_T("Sending:"));
		HexDumpData(m_OutputCtrl, Data, Length);
		m_ConnectedSocket.Send(Data, Length);
	}
	else
	{
		ASSERT(!m_PendingConnection);
		m_OutputCtrl.AddString(_T("Pending connection ..."));
		m_PendingConnection = true;
	}

	return 0;
}

LRESULT CTCPServerDlg::OnMySocketReceive(WPARAM wParam, LPARAM lParam)
{
	// Provide ample room to receive some data
	BYTE Data[256] = {0};

	// Get the data, and remember how many bytes are
	// actually copied into our buffer
	int BytesReceived = m_ConnectedSocket.Receive(Data, sizeof(Data));

	if (BytesReceived > 0)
	{
		m_OutputCtrl.AddString(_T("Received:"));
		HexDumpData(m_OutputCtrl, Data, BytesReceived);

		//echo back...
		BYTE DataClr[] = {0x1b, '$',	0x1b, 0x27, 0x30, 0x30};
		m_ConnectedSocket.Send(DataClr, sizeof(DataClr));
		m_ConnectedSocket.Send(Data, sizeof(Data));

	}
	else
	{
		CString ErrorMsg;
		ErrorMsg.Format(_T("Receive failed with error code %d"), m_ConnectedSocket.GetLastError());
		m_OutputCtrl.AddString((LPCTSTR)ErrorMsg);
	}

	return 0;
}

LRESULT CTCPServerDlg::OnMySocketClose(WPARAM wParam, LPARAM lParam)
{
	if (m_Connected)
	{
		// We're done, so perform a proper shutdown and close the socket
		m_OutputCtrl.AddString(_T("Shutting down the connected socket"));
		m_ConnectedSocket.ShutDown(CAsyncSocket::both);

		m_OutputCtrl.AddString(_T("Closing the connected socket"));
		m_ConnectedSocket.Close();

		m_Connected = false;

		if (m_PendingConnection)
		{
			OnMySocketAccept(0, 0);
			m_PendingConnection = false;
		}
	}
	else
	{
		m_OutputCtrl.AddString(_T("Can't close non-existant connection"));
	}

	return 0;
}
