// UCBioBSP_DemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "UCBioBSP_Demo.h"
#include "UCBioBSP_DemoDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CUCBioBSP_DemoDlg dialog

CUCBioBSP_DemoDlg::CUCBioBSP_DemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CUCBioBSP_DemoDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CUCBioBSP_DemoDlg)
	m_nDefaultTimeout = 0;
	m_nMaxFingerForEnroll = 0;
	m_nNecessaryEnrollNum = 0;
	m_nSamplesPerFinger = 0;
	m_nSecuLevelForEnroll = 0;
	m_nSecuLevelForVerify = 0;
	m_nSecuLevelForIdentify = 0;
	m_nDeviceWidth = 0;
	m_nDeviceHeight = 0;
	m_szPayload = _T("");
	m_AutoDetect = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

   m_hUCBioAPI = UCBioAPI_INVALID_HANDLE;

   m_nNumDevice = 0;
   m_pDeviceID = NULL;
   m_pDeviceInfoEx = NULL;
   m_nLastOpenedDeviceID = 0;

   m_hEnrolledFIR = m_hCapturedFIR = UCBioAPI_INVALID_HANDLE;

   
}

void CUCBioBSP_DemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CUCBioBSP_DemoDlg)
	DDX_Control(pDX, IDC_BUTTON_ENROLL, m_btnEnroll);
	DDX_Control(pDX, IDC_BUTTON_VERIFY, m_btnVerify);
	DDX_Control(pDX, IDC_BUTTON_REMOVE, m_btnRemove);
	DDX_Control(pDX, IDC_RADIO_TEXT, m_radioText);
   DDX_Control(pDX, IDC_RADIO_BINARY, m_radioBinary);
   DDX_Control(pDX, IDC_RADIO_HANDLE, m_radioHandle);
	DDX_Control(pDX, IDC_COMBO_DEVICE_LIST, m_comboDeviceList);
	DDX_Text(pDX, IDC_EDIT_DEFAULTTIMEOUT, m_nDefaultTimeout);
	DDX_Text(pDX, IDC_EDIT_MAXFINGER, m_nMaxFingerForEnroll);
	DDX_Text(pDX, IDC_EDIT_NECESSARYNUM, m_nNecessaryEnrollNum);
	DDX_Text(pDX, IDC_EDIT_SAMPLEPERFINGER, m_nSamplesPerFinger);
	DDX_Text(pDX, IDC_EDIT_SECULEVELENROLL, m_nSecuLevelForEnroll);
	DDX_Text(pDX, IDC_EDIT_SECULEVELIDENTIFY, m_nSecuLevelForVerify);
	DDX_Text(pDX, IDC_EDIT_SECULEVELVERIFY, m_nSecuLevelForIdentify);
	DDX_Text(pDX, IDC_EDIT_DEVICE_WIDTH, m_nDeviceWidth);
	DDX_Text(pDX, IDC_EDIT_DEVICE_HEIGHT, m_nDeviceHeight);
	DDX_Text(pDX, IDC_EDIT_PAYLOAD, m_szPayload);
	DDX_Check(pDX, IDC_CHECK_AUTO_DETECT, m_AutoDetect);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CUCBioBSP_DemoDlg, CDialog)
	//{{AFX_MSG_MAP(CUCBioBSP_DemoDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_CBN_SELCHANGE(IDC_COMBO_DEVICE_LIST, OnSelchangeComboDeviceList)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTON_REFRESH_INITINFO, OnButtonRefreshInitinfo)
	ON_BN_CLICKED(IDC_BUTTON_SETINIT, OnButtonSetinit)
	ON_BN_CLICKED(IDC_BUTTON_ENROLL, OnButtonEnroll)
	ON_BN_CLICKED(IDC_BUTTON_VERIFY, OnButtonVerify)
	ON_BN_CLICKED(IDC_BUTTON_REMOVE, OnButtonRemove)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

void DisplayError(LPCTSTR szMsg, UCBioAPI_RETURN err)
{
   CString szFormat;
   szFormat.Format(_T("%s (Error : 0x%02x)"), szMsg, err);
   AfxMessageBox(szFormat, MB_ICONERROR);
}

/////////////////////////////////////////////////////////////////////////////
// CUCBioBSP_DemoDlg message handlers

BOOL CUCBioBSP_DemoDlg::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
	

   UCBioAPI_RETURN err = UCBioAPI_Init(&m_hUCBioAPI);
   if (err != UCBioAPIERROR_NONE) {
      DisplayError(_T("Failed to initialize UCBioBSP!"), err);

   } else {
      UCBioAPI_VERSION  ver;
      memset(&ver, 0, sizeof(UCBioAPI_VERSION));

      if (UCBioAPI_GetVersion(m_hUCBioAPI, &ver) == UCBioAPIERROR_NONE) {
         CString szVer;
         szVer.Format(_T("UCBioBSP Version : v%d.%04d"), ver.Major, ver.Minor);
         SetWindowText(szVer);
      }

      OnButtonRefreshInitinfo();
      EnumDeviceList();
      OnSelchangeComboDeviceList();
   }

   m_radioHandle.SetCheck(TRUE);

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

void CUCBioBSP_DemoDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
   if (m_hEnrolledFIR != UCBioAPI_INVALID_HANDLE)
      UCBioAPI_FreeFIRHandle(m_hEnrolledFIR);
   if (m_hCapturedFIR != UCBioAPI_INVALID_HANDLE)
      UCBioAPI_FreeFIRHandle(m_hCapturedFIR);

   if (m_nLastOpenedDeviceID != 0)
      UCBioAPI_CloseDevice(m_hUCBioAPI, m_nLastOpenedDeviceID);

   UCBioAPI_Terminate(m_hUCBioAPI);

}

void CUCBioBSP_DemoDlg::EnumDeviceList()
{
   CString strItem;

   UCBioAPI_RETURN err = UCBioAPI_EnumerateDevice(m_hUCBioAPI, &m_nNumDevice, &m_pDeviceID, &m_pDeviceInfoEx);
   if (err) {
      DisplayError(_T("Failed to enumerate device!"), err);
      return;
   }

   int nIndex;

   if (m_nNumDevice == 0) {
      nIndex = m_comboDeviceList.AddString(_T("--NO DEVICE--"));
      m_comboDeviceList.SetItemData(nIndex, UCBioAPI_DEVICE_ID_NONE);
      return;
   }

   nIndex = m_comboDeviceList.AddString(_T("Auto_Detect"));
   m_comboDeviceList.SetItemData(nIndex, UCBioAPI_DEVICE_ID_AUTO);

   DWORD i;
   CString szDevice;

   for (i = 0 ; i < m_nNumDevice; i++) {
      szDevice.Format(_T("%s - %s"), m_pDeviceInfoEx[i].Name, m_pDeviceInfoEx[i].Description);
      nIndex = m_comboDeviceList.AddString(szDevice);
      m_comboDeviceList.SetItemData(nIndex, m_pDeviceInfoEx[i].NameID);
   }   
   m_comboDeviceList.SetCurSel(0);

   UpdateData(FALSE);
   UpdateButtonStatus();
}

void CUCBioBSP_DemoDlg::UpdateButtonStatus()
{
   m_btnRemove.EnableWindow(m_hEnrolledFIR != UCBioAPI_INVALID_HANDLE);
   m_btnVerify.EnableWindow(m_hEnrolledFIR != UCBioAPI_INVALID_HANDLE);

   if (m_hEnrolledFIR == UCBioAPI_INVALID_HANDLE)
      m_btnEnroll.SetWindowText(_T("Enroll"));
   else
      m_btnEnroll.SetWindowText(_T("Modify"));
}

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

void CUCBioBSP_DemoDlg::OnButtonRefreshInitinfo() 
{
   UCBioAPI_INIT_INFO_0 initInfo0;
   memset(&initInfo0, 0, sizeof(UCBioAPI_INIT_INFO_0));

   UCBioAPI_RETURN err = UCBioAPI_GetInitInfo(m_hUCBioAPI, 0, &initInfo0);
   if (err == UCBioAPIERROR_NONE) {
      m_nMaxFingerForEnroll = initInfo0.MaxFingersForEnroll;
      m_nNecessaryEnrollNum = initInfo0.NecessaryEnrollNum;
      m_nSamplesPerFinger = initInfo0.SamplesPerFinger;
      m_nDefaultTimeout = initInfo0.DefaultTimeout;
      m_nSecuLevelForEnroll = initInfo0.SecurityLevelForEnroll;
      m_nSecuLevelForVerify = initInfo0.SecurityLevelForVerify;
      m_nSecuLevelForIdentify = initInfo0.SecurityLevelForIdentify;

      UpdateData(FALSE);
   } else {
      DisplayError(_T("Failed to get init information!"), err);
   }
}

void CUCBioBSP_DemoDlg::OnButtonSetinit() 
{
	UpdateData();

   UCBioAPI_INIT_INFO_0 initInfo0;
   memset(&initInfo0, 0, sizeof(UCBioAPI_INIT_INFO_0));

   initInfo0.StructureType = 0;
   initInfo0.MaxFingersForEnroll = m_nMaxFingerForEnroll;
   initInfo0.NecessaryEnrollNum = m_nNecessaryEnrollNum;
   initInfo0.SamplesPerFinger = m_nSamplesPerFinger;
   initInfo0.DefaultTimeout = m_nDefaultTimeout;
   initInfo0.SecurityLevelForEnroll = m_nSecuLevelForEnroll;
   initInfo0.SecurityLevelForVerify = m_nSecuLevelForVerify;
   initInfo0.SecurityLevelForIdentify = m_nSecuLevelForIdentify;

   UCBioAPI_RETURN err = UCBioAPI_SetInitInfo(m_hUCBioAPI, 0, &initInfo0);
   if (err != UCBioAPIERROR_NONE) {
      DisplayError(_T("Failed to set init information!"), err);
   }
}

void CUCBioBSP_DemoDlg::OnSelchangeComboDeviceList() 
{
	UpdateData();

   INT nIndex = m_comboDeviceList.GetCurSel();
   UCBioAPI_DEVICE_ID nDeviceID = (UCBioAPI_DEVICE_ID)m_comboDeviceList.GetItemData(nIndex);

   if (nDeviceID != UCBioAPI_DEVICE_ID_NONE) {
      UCBioAPI_CloseDevice(m_hUCBioAPI, m_nLastOpenedDeviceID);

      UCBioAPI_RETURN err = UCBioAPI_OpenDevice(m_hUCBioAPI, nDeviceID);
      if (err == UCBioAPIERROR_NONE) {
         m_nLastOpenedDeviceID = nDeviceID;

         UCBioAPI_DEVICE_INFO_0 deviceInfo0;
         memset(&deviceInfo0, 0, sizeof(UCBioAPI_DEVICE_INFO_0));
         err = UCBioAPI_GetDeviceInfo(m_hUCBioAPI, nDeviceID, 0, &deviceInfo0);
         if (err == UCBioAPIERROR_NONE) {
            m_nDeviceWidth = deviceInfo0.ImageWidth;
            m_nDeviceHeight = deviceInfo0.ImageHeight;
            UpdateData(FALSE);
         }
      } else {
         DisplayError(_T("Failed to open device!"), err);
      }
   }

   UpdateButtonStatus();
}

void CUCBioBSP_DemoDlg::OnButtonEnroll() 
{
	UpdateData();

	UCBioAPI_FIR_HANDLE hNewFIR;

	UCBioAPI_INPUT_FIR inputFIR;
	inputFIR.Form = UCBioAPI_FIR_FORM_HANDLE;
	inputFIR.InputFIR.FIRinBSP = &m_hEnrolledFIR;

	UCBioAPI_FIR_PAYLOAD payload;
	payload.Length = (lstrlen(m_szPayload) + 1) * sizeof(TCHAR);
	payload.Data = new UCBioAPI_UINT8 [payload.Length];
	memset(payload.Data, 0, payload.Length);
	lstrcpy((LPTSTR)payload.Data, m_szPayload);

	if(m_AutoDetect) UCBioAPI_SetAutoDetect(m_hUCBioAPI, TRUE);
	else UCBioAPI_SetAutoDetect(m_hUCBioAPI, FALSE);

	UCBioAPI_RETURN err = UCBioAPI_Enroll(m_hUCBioAPI, &inputFIR, &hNewFIR, &payload, UCBioAPI_USE_DEFAULT_TIMEOUT, NULL, NULL);
	if (err == UCBioAPIERROR_NONE) 
	{
		UCBioAPI_FreeFIRHandle(m_hEnrolledFIR);
		m_hEnrolledFIR = hNewFIR;
	}

	delete[] payload.Data;

	UpdateButtonStatus();
}

void CUCBioBSP_DemoDlg::OnButtonVerify() 
{
   UCBioAPI_FIR binaryFIR;
   UCBioAPI_FIR_TEXTENCODE textFIR;
   memset(&binaryFIR, 0, sizeof(UCBioAPI_FIR));
   memset(&textFIR, 0, sizeof(UCBioAPI_FIR_TEXTENCODE));

   UCBioAPI_INPUT_FIR inputFIR;

   if (m_radioHandle.GetCheck()) {
      inputFIR.Form = UCBioAPI_FIR_FORM_HANDLE;
      inputFIR.InputFIR.FIRinBSP = &m_hEnrolledFIR;
   } else if (m_radioBinary.GetCheck()) {
      UCBioAPI_GetFIRFromHandle(m_hEnrolledFIR, &binaryFIR);
      inputFIR.Form = UCBioAPI_FIR_FORM_FULLFIR;
      inputFIR.InputFIR.FIR = &binaryFIR;
   } else if (m_radioText.GetCheck()) {
      UCBioAPI_GetTextFIRFromHandle(m_hEnrolledFIR, &textFIR, ((sizeof(TCHAR) == sizeof(CHAR)) ? UCBioAPI_FALSE : UCBioAPI_TRUE));
      inputFIR.Form = UCBioAPI_FIR_FORM_TEXTENCODE;
      inputFIR.InputFIR.TextFIR = &textFIR;
   }

   UCBioAPI_BOOL bResult;
   UCBioAPI_FIR_PAYLOAD payload;
   memset(&payload, 0, sizeof(UCBioAPI_FIR_PAYLOAD));

   UCBioAPI_RETURN err = UCBioAPI_Verify(m_hUCBioAPI, &inputFIR, &bResult, &payload, UCBioAPI_USE_DEFAULT_TIMEOUT, NULL, NULL);
   if (err == UCBioAPIERROR_NONE && bResult == UCBioAPI_TRUE) {
      CString szMsg = _T("Succeeded to verify!");
      CString szPayload;
      if (payload.Length > 0)
         szPayload.Format(_T(" (Payload: %s)"), (LPCTSTR)payload.Data);
      szMsg += szPayload;
      AfxMessageBox(szMsg);
   } else {
      CString szMsg = _T("Failed to verify!");
      AfxMessageBox(szMsg);
   }

   if (m_radioBinary.GetCheck()) {
      UCBioAPI_FreeFIR(&binaryFIR);
   } else if (m_radioText.GetCheck()) {
      UCBioAPI_FreeTextFIR(&textFIR);
   }
   UCBioAPI_FreePayload(&payload);
}

void CUCBioBSP_DemoDlg::OnButtonRemove() 
{
	// TODO: Add your control notification handler code here
   if (m_hEnrolledFIR != UCBioAPI_INVALID_HANDLE) {
      UCBioAPI_FreeFIRHandle(m_hEnrolledFIR);
      m_hEnrolledFIR = UCBioAPI_INVALID_HANDLE;
   }

	UpdateButtonStatus();
}
