// NtKmedDlg.cpp : implementation file
//

#include "stdafx.h"
#include "NtKmed.h"
#include "NtKmedDlg.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()

/////////////////////////////////////////////////////////////////////////////
// CNtKmedDlg dialog

CNtKmedDlg::CNtKmedDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CNtKmedDlg::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(CNtKmedDlg)
	m_DriverName = _T("DigiDxb2");
	m_PortNumber = 2773;
	m_MessageText = _T("Idle");
	m_EndianIndex = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

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

void CNtKmedDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CNtKmedDlg)
	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);
	DDX_Radio(pDX, IDC_RADIO_DETECT, m_EndianIndex);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CNtKmedDlg, CDialog)
	//{{AFX_MSG_MAP(CNtKmedDlg)
	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()

/////////////////////////////////////////////////////////////////////////////
// CNtKmedDlg message handlers

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

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

	UpdateMessage("Initializing DigiDxb driver");

	m_DebugInfo.DriverName = m_DriverName;
	m_DebugInfo.Port = m_PortNumber;
	m_DebugInfo.nEndianIndex = m_EndianIndex;
	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);
	GetDlgItem(IDC_RADIO_DETECT)->EnableWindow(FALSE);
	GetDlgItem(IDC_RADIO_ASIS)->EnableWindow(FALSE);
	GetDlgItem(IDC_RADIO_IN_NETWORK_ORDER)->EnableWindow(FALSE);

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

void CNtKmedDlg::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);
	GetDlgItem(IDC_RADIO_DETECT)->EnableWindow(TRUE);
	GetDlgItem(IDC_RADIO_ASIS)->EnableWindow(TRUE);
	GetDlgItem(IDC_RADIO_IN_NETWORK_ORDER)->EnableWindow(TRUE);

}

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

	UpdateData(FALSE);
	UpdateWindow();
}

void CNtKmedDlg::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);
		GetDlgItem(IDC_RADIO_DETECT)->EnableWindow(TRUE);
		GetDlgItem(IDC_RADIO_ASIS)->EnableWindow(TRUE);
		GetDlgItem(IDC_RADIO_IN_NETWORK_ORDER)->EnableWindow(TRUE);
		if (0 != m_TimerID)
		{
			KillTimer(m_TimerID);
			m_TimerID = 0;
		}
	}

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