// NtKgsDlg.cpp : implementation file
//

#include "stdafx.h"
#include "NtKgs.h"
#include "NtKgsDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CNtKgsDlg dialog

CNtKgsDlg::CNtKgsDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CNtKgsDlg::IDD, pParent)
{
	m_DebugInfo.DriverName = "";
	m_DebugInfo.pMessage = &m_MessageText;
	m_DebugInfo.Port = 0;
	m_DebugInfo.hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_DebugInfo.hThreadCompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_hDebugThread = NULL;
	m_TimerID = 0;

#pragma message("NOTE: NOTE: Defaults for port and driver name are hardcoded")
	//{{AFX_DATA_INIT(CNtKgsDlg)
	m_DriverName = _T("DigiDxb2");
	m_PortNumber = 1234;
	m_MessageText = _T("Idle");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

#define TIMER_ID 0
CNtKgsDlg::~CNtKgsDlg(void)
{
	if (NULL != m_DebugInfo.hShutdownEvent)
		CloseHandle(m_DebugInfo.hShutdownEvent);
	if (NULL != m_DebugInfo.hThreadCompleteEvent)
		CloseHandle(m_DebugInfo.hThreadCompleteEvent);
	CDialog::~CDialog();
}

void CNtKgsDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CNtKgsDlg)
	DDX_Control(pDX, IDB_DISCONNECT, m_DisconnectButton);
	DDX_Control(pDX, IDB_CONNECT, m_ConnectButton);
	DDX_Text(pDX, IDC_EDIT_DRIVER_NAME, m_DriverName);
	DDX_Text(pDX, IDC_EDIT_PORT_NUMBER, m_PortNumber);
	DDX_Text(pDX, IDC_MESSAGE_TEXT, m_MessageText);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CNtKgsDlg, CDialog)
	//{{AFX_MSG_MAP(CNtKgsDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDB_CONNECT, OnConnect)
	ON_BN_CLICKED(IDB_DISCONNECT, OnDisconnect)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CNtKgsDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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

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

void CNtKgsDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

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

void CNtKgsDlg::OnConnect()
{
	if (!UpdateData(TRUE))
	{
		AfxMessageBox("Error: Invalid Port Number or Driver Name", (MB_ICONSTOP|MB_APPLMODAL|MB_OK));
		return;
	}

	UpdateMessage("Waiting for Connection");

	m_DebugInfo.DriverName = m_DriverName;
	m_DebugInfo.Port = m_PortNumber;
	ResetEvent(m_DebugInfo.hShutdownEvent);
	ResetEvent(m_DebugInfo.hThreadCompleteEvent);

	m_hDebugThread = AfxBeginThread(DebugThread, &m_DebugInfo);
	if (NULL == m_hDebugThread)
	{
		AfxMessageBox("Error: Thread failed to start", (MB_ICONSTOP|MB_APPLMODAL|MB_OK));
		UpdateMessage("Idle");
		return;
	}

	m_ConnectButton.EnableWindow(FALSE);
	m_DisconnectButton.EnableWindow(TRUE);
	GetDlgItem(IDC_EDIT_PORT_NUMBER)->EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_DRIVER_NAME)->EnableWindow(FALSE);

	m_TimerID = SetTimer(1, 300, NULL);
}

void CNtKgsDlg::OnDisconnect() 
{
	UpdateMessage("Disconnecting");

	if (NULL != m_DebugInfo.hShutdownEvent)
		SetEvent(m_DebugInfo.hShutdownEvent);

#define MS_TO_WAIT_FOR_THREAD_SHUTDOWN 10000
	if (NULL != m_DebugInfo.hThreadCompleteEvent)
	{
		DWORD Result = WaitForSingleObject(m_DebugInfo.hThreadCompleteEvent, MS_TO_WAIT_FOR_THREAD_SHUTDOWN);
		if (WAIT_OBJECT_0 != Result)
		{
			AfxMessageBox("Error: Thread failed to shutdown", (MB_ICONSTOP|MB_APPLMODAL|MB_OK));
			UpdateMessage("Error: Thread failed to shutdown");
			return;
		}
	}

	if (0 != m_TimerID)
	{
		KillTimer(m_TimerID);
		m_TimerID = 0;
	}

	UpdateMessage("Idle");

	m_ConnectButton.EnableWindow(TRUE);
	m_DisconnectButton.EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_PORT_NUMBER)->EnableWindow(TRUE);
	GetDlgItem(IDC_EDIT_DRIVER_NAME)->EnableWindow(TRUE);
}

// Don't use this in a thread!
void CNtKgsDlg::UpdateMessage(CString const Message /*=""*/)
{
	if (!Message.IsEmpty())
		m_MessageText = Message;

	UpdateData(FALSE);
	UpdateWindow();
}

void CNtKgsDlg::OnTimer(UINT nIDEvent) 
{
	// Check for thread exit
	DWORD Result = WaitForSingleObject(m_DebugInfo.hThreadCompleteEvent, 0);
	if (WAIT_OBJECT_0 == Result)
	{
		m_ConnectButton.EnableWindow(TRUE);
		m_DisconnectButton.EnableWindow(FALSE);
		GetDlgItem(IDC_EDIT_PORT_NUMBER)->EnableWindow(TRUE);
		GetDlgItem(IDC_EDIT_DRIVER_NAME)->EnableWindow(TRUE);
		if (0 != m_TimerID)
		{
			KillTimer(m_TimerID);
			m_TimerID = 0;
		}
	}

	UpdateMessage();
	CDialog::OnTimer(nIDEvent);
}
