// TCPClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TCPClient.h"
#include "TCPClientDlg.h"
#include "HexDumpData.h"
#include "Network.h"

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

/////////////////////////////////////////////////////////////////////////////
// CTCPClientDlg dialog

CTCPClientDlg::CTCPClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTCPClientDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTCPClientDlg)
		// 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);
}

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

BEGIN_MESSAGE_MAP(CTCPClientDlg, CDialog)
	//{{AFX_MSG_MAP(CTCPClientDlg)
	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_ONCONNECT, OnMySocketConnect)
	ON_MESSAGE(WM_MYSOCKET_ONRECEIVE, OnMySocketReceive)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPClientDlg message handlers

BOOL CTCPClientDlg::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
	
	// Initialize the listbox to use a fixed-width font for aesthetics only
	m_OutputCtrl.SetFont(CFont::FromHandle((HFONT)GetStockObject(OEM_FIXED_FONT)));

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

	SetupConnection();
	
	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 CTCPClientDlg::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 CTCPClientDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

/////////////////////////////////////////////////////////////////////////////
// MySocket massage handlers

LRESULT CTCPClientDlg::OnMySocketConnect(WPARAM wParam, LPARAM lParam)
{
	int ErrorCode = (int)wParam;

	// See if the connection completed successfully
	if (ErrorCode == 0)
	{
		m_OutputCtrl.AddString(_T("Conncection succeeded"));

		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);

		// Transmit some data to the device
		m_MySocket.Send(Data, Length);
	}
	else
	{
		CString ErrorMsg;
		ErrorMsg.Format(_T("Connection failed with error code %d"), ErrorCode);
		m_OutputCtrl.AddString((LPCTSTR)ErrorMsg);
	 }

	return 0;
}

LRESULT CTCPClientDlg::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_MySocket.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_MySocket.Send(DataClr, sizeof(DataClr));
		m_MySocket.Send(Data, sizeof(Data));
	}
	else
	{
		CString ErrorMsg;
		ErrorMsg.Format(_T("Receive failed with error code %d"), m_MySocket.GetLastError());
		m_OutputCtrl.AddString((LPCTSTR)ErrorMsg);
	}

	// We're done, so perform a proper shutdown and close the socket
	/*
	m_OutputCtrl.AddString(_T("Shutting down the socket"));
	m_MySocket.ShutDown(CAsyncSocket::both);

	m_OutputCtrl.AddString(_T("Closing socket"));
	m_MySocket.Close();

	m_OutputCtrl.AddString(_T("Finish"));
	*/

	return 0;
}

void CTCPClientDlg::SetupConnection()
{
		// Initialize our socket to relay messages back to this window
	
	m_MySocket.m_Hwnd = m_hWnd;

	//Setup Connection Info
	CNetwork Dlg(this);
	Dlg.DoModal();
	
	CString AddressToConnectTo = Dlg.m_IPAddress;
	UINT PortToConnectTo = Dlg.m_Port;
	
	//Done

	m_OutputCtrl.AddString(_T("Creating socket ..."));

	// Call the socket's Create method to create the
	// socket handle and bind to a local port
	if (m_MySocket.Create())
	{
		CString LocalAddress;
		UINT LocalPort = 0;
	
		// Get the local socket address and port in human readable form
		m_MySocket.GetSockName(LocalAddress, LocalPort);

		CString Message;

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


		Message.Format(_T("Connecting to %s:%u"), AddressToConnectTo, PortToConnectTo);
		m_OutputCtrl.AddString((LPCTSTR)Message);

		// Initiate a connection to the device
		m_MySocket.Connect(AddressToConnectTo, PortToConnectTo);
	}
	else
	{
		m_OutputCtrl.AddString(_T("Socket creation failed"));
	}
	
}
