// UDPSerialDlg.cpp : implementation file
//

#include "stdafx.h"
#include "UDPSerial.h"
#include "UDPSerialDlg.h"
#include "HexDumpData.h"
#include "Network.h"

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

/////////////////////////////////////////////////////////////////////////////
// CUDPSerialDlg dialog

CUDPSerialDlg::CUDPSerialDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CUDPSerialDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CUDPSerialDlg)
		// 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 CUDPSerialDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CUDPSerialDlg)
	DDX_Control(pDX, IDC_OUTPUT, m_OutputCtrl);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CUDPSerialDlg, CDialog)
	//{{AFX_MSG_MAP(CUDPSerialDlg)
	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_ONRECEIVE, OnMySocketReceive)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CUDPSerialDlg message handlers

BOOL CUDPSerialDlg::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)));

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

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

	CString AddressReceivedFrom;
	UINT PortReceivedFrom = 0;

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

	if (BytesReceived > 0)
	{
		CString Message;
		Message.Format(_T("Received data from %s:%u:"), (LPCTSTR)AddressReceivedFrom, PortReceivedFrom);
		m_OutputCtrl.AddString((LPCTSTR)Message);
		HexDumpData(m_OutputCtrl, Data, BytesReceived);

		//echo back...
		BYTE DataClr[] = {0x1b, '$',	0x1b, 0x27, 0x30, 0x30};
		m_MySocket.SendTo(DataClr, sizeof(DataClr), PortReceivedFrom, AddressReceivedFrom);
		m_MySocket.SendTo(Data, sizeof(Data), PortReceivedFrom, AddressReceivedFrom);
	}
	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 the socket"));
	m_MySocket.Close();

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

	return 0;
}

void CUDPSerialDlg::SetupConnection()
{
	
	//Setup Connection Info
	CNetwork Dlg(this);
	Dlg.DoModal();

	CString AddressToSendTo = Dlg.m_IPAddress;
	UINT PortToSendTo = Dlg.m_Port;
	
	//Done	
	
	m_OutputCtrl.AddString(_T("Start"));

	// Initialize our socket to relay messages back to this window
	m_MySocket.m_Hwnd = m_hWnd;

	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(9000, SOCK_DGRAM))
	{
		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);

		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_MySocket.SendTo(Data, Length, PortToSendTo, AddressToSendTo);
	}
	else
	{
		m_OutputCtrl.AddString(_T("Socket creation failed"));
	}

}
