// sample_13Dlg.cpp : implementation file
//


#include "stdafx.h"
#include "sample_13.h"
#include "sample_13Dlg.h"
#include <dbt.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()

/////////////////////////////////////////////////////////////////////////////
// CSample_13Dlg dialog

CSample_13Dlg::CSample_13Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSample_13Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSample_13Dlg)
		// 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 CSample_13Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSample_13Dlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSample_13Dlg, CDialog)
	//{{AFX_MSG_MAP(CSample_13Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_REGISTER, OnRegister)
	ON_WM_DEVICECHANGE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSample_13Dlg message handlers

BOOL CSample_13Dlg::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
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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


/* The following handles insert/remove notification */

// function prototype for getting HID GUID
typedef void (__stdcall *FUNC_TYPE_HIDGUID) (
			OUT   LPGUID   HidGuid
			);

FUNC_TYPE_HIDGUID _HidD_GetHidGuid = NULL;

 // SenseLock EL USB version GUID
static GUID GUID_CLASS_ITOKEN2 = 
{0x171638f7, 0x1ead, 0x4873, {0xba, 0x98, 0xc9, 0x66, 0xab, 0xcf, 0x1, 0x42}};

static GUID GUID_CLASS_ITOKEN2_HID;

BOOL    bRegisted  = FALSE;
typedef  PVOID           HDEVNOTIFY;
HDEVNOTIFY hDevNotify1 = NULL;
HDEVNOTIFY hDevNotify2 = NULL;

void CSample_13Dlg::OnRegister() 
{
	// TODO: Add your control notification handler code here
	HWND hWnd;
//	HDEVNOTIFY hDevNotify = NULL;
    DEV_BROADCAST_DEVICEINTERFACE dbf;
	BOOL bRes;
	


	if (_HidD_GetHidGuid == NULL)
	{
		HINSTANCE hMod = LoadLibrary("hid.dll");
		_HidD_GetHidGuid = (FUNC_TYPE_HIDGUID)GetProcAddress(hMod, "HidD_GetHidGuid");
		ASSERT(_HidD_GetHidGuid != NULL);

		// Get HID device GUID 
		_HidD_GetHidGuid(&GUID_CLASS_ITOKEN2_HID);
		FreeLibrary(hMod);
	}

	
	if (!bRegisted) // if not registered
	{

		hWnd = this->m_hWnd;

		// Register ITOKEN2 device notification 
		memset(&dbf, 0x00, sizeof(dbf));
		
		dbf.dbcc_size       = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
		dbf.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
		dbf.dbcc_classguid  = GUID_CLASS_ITOKEN2;
		
		hDevNotify2 = RegisterDeviceNotification( hWnd, 
			&dbf,
			DEVICE_NOTIFY_WINDOW_HANDLE
			);
		
		ASSERT(hDevNotify2 != NULL);

		// Register ITOKEN2 HID device notification
		memset(&dbf, 0x00, sizeof(dbf));
		
		dbf.dbcc_size       = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
		dbf.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
		dbf.dbcc_classguid  = GUID_CLASS_ITOKEN2_HID;
		
		hDevNotify1 = RegisterDeviceNotification( hWnd, 
			&dbf,
			DEVICE_NOTIFY_WINDOW_HANDLE
			);
		
		ASSERT(hDevNotify1 != NULL);

		GetDlgItem(IDC_REGISTER)->SetWindowText("Unregister");
			
		bRegisted = TRUE;
	}
	else 
	{
		if (hDevNotify1) // Unregister ITOKEN2 device notification 
		{
			bRes = UnregisterDeviceNotification(hDevNotify1);
			
			ASSERT(bRes);
		}

		if (hDevNotify2) // Unregister ITOKEN2 HID device notification
		{
			bRes = UnregisterDeviceNotification(hDevNotify2);

			ASSERT(bRes);
		}

		GetDlgItem(IDC_REGISTER)->SetWindowText("register");
		
		bRegisted = FALSE;
	}
}

VOID FormatGuid(LPGUID guid, char *guidBuf)
{

	char *p = guidBuf;
	p += sprintf(p, "{%08x-", guid->Data1);
	p += sprintf(p, "%04x-", guid->Data2);
	p += sprintf(p, "%04x-", guid->Data3);
	p += sprintf(p, "%02x%02x%02x%02x%02x%02x%02x%02x}", 
		guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
		guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
}
	
BOOL CSample_13Dlg::OnDeviceChange(UINT nEventType, DWORD dwData)
{
	PDEV_BROADCAST_DEVICEINTERFACE pDbt;
	pDbt = (PDEV_BROADCAST_DEVICEINTERFACE)dwData;
	char guidBuf[128];
	const char *hidDevPath = "\\\\?\\HID#Vid_0471&Pid_485e";

	switch(nEventType) 
	{

	case DBT_DEVICEARRIVAL:
		TRACE("new device found :%s\n", pDbt->dbcc_name);
		FormatGuid(&pDbt->dbcc_classguid, guidBuf);
		TRACE("device GUID:%s\n", guidBuf);
		
		// Check GUID to see whether it's a SenseLock EL device. Notice:the GUIDs of HID devices are 
		// of the same,so we have to make further check on PID and VID
		
		if (!memcmp(&pDbt->dbcc_classguid, &GUID_CLASS_ITOKEN2,     sizeof(GUID)) ||
			(!memcmp(&pDbt->dbcc_classguid, &GUID_CLASS_ITOKEN2_HID, sizeof(GUID)) &&
			!memicmp(&pDbt->dbcc_name, hidDevPath, strlen(hidDevPath)))) 
		{
			TRACE("New SenseLock EL device found\n");			
			MessageBox("SenseLock EL inserted", NULL, MB_OK);
			// TODO: Add your handler code here
		}
		
		break;
	case DBT_DEVICEREMOVECOMPLETE :
		TRACE("device removed :%s\n", pDbt->dbcc_name);
		FormatGuid(&pDbt->dbcc_classguid, guidBuf);
		TRACE("device GUID:%s\n", guidBuf);
		
		if (!memcmp(&pDbt->dbcc_classguid, &GUID_CLASS_ITOKEN2,     sizeof(GUID)) ||
			(!memcmp(&pDbt->dbcc_classguid, &GUID_CLASS_ITOKEN2_HID, sizeof(GUID)) &&
			!memicmp(&pDbt->dbcc_name, hidDevPath, strlen(hidDevPath)))) 
		{
			TRACE("SenseLock EL device removed\n");			
			MessageBox("SenseLock EL removed", NULL, MB_OK);			
			// TODO: Add your handler code here
		}
		break;
	default:
		break;		
	}
	return TRUE;
}
