// PCSCDemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "PCSCDemo.h"
#include "PCSCDemoDlg.h"
#include "Reader.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()

/////////////////////////////////////////////////////////////////////////////
// CPCSCDemoDlg dialog

CPCSCDemoDlg::CPCSCDemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CPCSCDemoDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CPCSCDemoDlg)
		// 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 CPCSCDemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CPCSCDemoDlg)
	DDX_Control(pDX, IDC_COMBO_M1_BLOCK, m_M1Block);
	DDX_Control(pDX, IDC_STATIC_STATUS, m_Status);
	DDX_Control(pDX, IDC_EDIT_M1_DATA, m_M1Data);
	DDX_Control(pDX, IDC_EDIT_M1_KEY, m_M1Key);
	DDX_Control(pDX, IDC_EDIT_M1_UID, m_M1UID);
	DDX_Control(pDX, IDC_COMBO_READER, m_CBReader);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CPCSCDemoDlg, CDialog)
	//{{AFX_MSG_MAP(CPCSCDemoDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BT_UPDATA, OnBtUpdata)
	ON_BN_CLICKED(IDC_BT_CONNECT, OnBtConnect)
	ON_BN_CLICKED(IDC_BT_M1_SEARCH, OnBtM1Search)
	ON_BN_CLICKED(IDC_BT_M1_READ, OnBtM1Read)
	ON_BN_CLICKED(IDC_BT_M1_WRITE, OnBtM1Write)
	ON_BN_CLICKED(IDC_BT_M1_HALT, OnBtM1Halt)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPCSCDemoDlg message handlers

BOOL CPCSCDemoDlg::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
	//Initialize connect
	unsigned int i;
	if(m_bActiveFlag)
	{
		//Connected
		m_CBReader.ResetContent();
		for(i=0; i<m_bReaderCounter; i++)
		{
			m_CBReader.SetCurSel(i);
			m_CBReader.AddString(ReaderName[i]);
		}
		m_CBReader.SetCurSel(m_bActiveNO);
		((CButton *)GetDlgItem(IDC_BT_CONNECT))->SetWindowText("Disconnect");
		m_CBReader.EnableWindow(FALSE);
	}
	else
	{
		//disconnect
		UpdataReader();
		if(m_bReaderCounter != 0)
		{
			m_CBReader.ResetContent();
			for(i=0; i<m_bReaderCounter; i++)
			{
				m_CBReader.SetCurSel(i);
				m_CBReader.AddString(ReaderName[i]);
			}
			m_CBReader.SetCurSel(0);
		}
		m_CBReader.EnableWindow(TRUE);
	}

	//Initialize
	m_M1UID.SetLimitTextEx(8);
	m_M1Key.SetLimitTextEx(6);
	m_M1Data.SetLimitTextEx(16);

	m_M1Key.SetWindowText("FFFFFFFFFFFF");
	((CButton *)GetDlgItem(IDC_RADIO_M1_KEYA))->SetCheck(TRUE);

	CString str;
	for(i=0; i<64; i++)
	{
		str.Format("Block %d", i);
		m_M1Block.AddString(str);
		m_M1Block.SetItemData(i,i);
	}
	m_M1Block.SetCurSel(1);

	m_Status.SetWindowText("Please select PC/SC reader!");

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

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

void CPCSCDemoDlg::OnBtUpdata() 
{
	// TODO: Add your control notification handler code here
	BOOL bUpdataFlag;
	unsigned int i;
	
	bUpdataFlag = UpdataReader();
	
	if(bUpdataFlag)
	{
		m_CBReader.EnableWindow(TRUE);
		if(m_bReaderCounter != 0)
		{
			m_CBReader.ResetContent();
			for(i=0; i<m_bReaderCounter; i++)
			{
				m_CBReader.SetCurSel(i);
				m_CBReader.AddString(ReaderName[i]);
			}
			m_CBReader.SetCurSel(0);
		}
		((CButton *)GetDlgItem(IDC_BT_CONNECT))->SetWindowText("Connect");
		m_Status.SetWindowText("Please select PC/SC reader!");
	}	
}

void CPCSCDemoDlg::OnBtConnect() 
{
	// TODO: Add your control notification handler code here
	BOOL bConnectFlag;
	long ActiveName;
	
	if(m_bActiveFlag)
	{
		//断开连接
		bConnectFlag = DisconnectReader();
		if(bConnectFlag)
		{
			((CButton *)GetDlgItem(IDC_BT_CONNECT))->SetWindowText("Connect");
			m_CBReader.EnableWindow(TRUE);
			m_Status.SetWindowText("Please select PC/SC reader!");
		}
	}
	else
	{
		//连接
		ActiveName = m_CBReader.GetCurSel();
		bConnectFlag = ConnectReader(ActiveName);
		if(bConnectFlag)
		{
			((CButton *)GetDlgItem(IDC_BT_CONNECT))->SetWindowText("DisConnect");
			m_CBReader.EnableWindow(FALSE);
			m_Status.SetWindowText("PC/SC reader connected!");
		}
	}	
}

void CPCSCDemoDlg::OnBtM1Search() 
{
	// TODO: Add your control notification handler code here
	int iSW;
	unsigned char CardInfo[10];
	unsigned int ReceiveLen[1];
	m_M1Data.SetWindowText("");
	iSW = GetData(GET_MIFAREONE, CardInfo, ReceiveLen);
	if(SUCCESS == iSW)
	{
		//寻卡成功
		m_M1UID.SetWindowTextEx(&CardInfo[1], CardInfo[0]);
		m_Status.SetWindowText("Search card successful!");
		m_bM1CardActiveFlag = TRUE;
	}
	else
	{
		m_M1UID.SetWindowText("");
		m_Status.SetWindowText("Search card fail!");
		m_bM1CardActiveFlag = FALSE;
	}	
}

void CPCSCDemoDlg::OnBtM1Read() 
{
	// TODO: Add your control notification handler code here
	if(!m_bM1CardActiveFlag)
	{
		m_Status.SetWindowText("Please clicked SearchCard button!"); 
		return;
	}

	unsigned char cKeyType = 0x60;
	unsigned char cKeyConfig = 0x06;
	CString key;
	int iSW;
	unsigned int block;
	unsigned int iReceiveLen;
	unsigned char cReceiveData[16];
	
	UpdateData(FALSE);
	
	m_M1Key.GetWindowTextEx(key);
	m_M1Data.SetWindowText("");
	
	//Key Length
	if(m_M1Key.GetTextLenEx() != 6)
	{
		MessageBox("Key length must be 6 byte",ERROR, MB_OK|MB_ICONERROR);
		m_Status.SetWindowText("Key length must be 6 byte!"); 
		return;
	}
	block = m_M1Block.GetItemData(m_M1Block.GetCurSel());

	//Authentication
	iSW = Authentication(block, cKeyType, cKeyConfig, (unsigned char *)key.GetBuffer(key.GetLength()));
	key.ReleaseBuffer();
	if(SUCCESS != iSW)
	{	
		m_Status.SetWindowText("Authentication fail!");
		m_bM1CardActiveFlag = FALSE;
		return;
	}

	//ReadCard
	iReceiveLen = 16;
	iSW = ReadBinaryBlock(block, (BYTE *)cReceiveData, &iReceiveLen);
	if(SUCCESS == iSW)
	{
		m_M1Data.SetWindowTextEx(cReceiveData,iReceiveLen);
		m_Status.SetWindowText("Read card successful!");
	}
	else
	{
		m_Status.SetWindowText("Read card fail!");
	}	
}

void CPCSCDemoDlg::OnBtM1Write() 
{
	// TODO: Add your control notification handler code here
	if(!m_bM1CardActiveFlag)
	{
		m_Status.SetWindowText("Please clicked SearchCard button!"); 
		return;
	}

	unsigned char cKeyType = 0x60;
	unsigned char cKeyConfig = 0x06;
	CString key;
	int iSW;
	unsigned int block;
	
	UpdateData(FALSE);
	
	m_M1Key.GetWindowTextEx(key);
	
	//Key Length
	if(m_M1Key.GetTextLenEx() != 6)
	{
		MessageBox("Key length must be 6 byte",ERROR, MB_OK|MB_ICONERROR);
		m_Status.SetWindowText("Key length must be 6 byte!"); 
		return;
	}
	block = m_M1Block.GetItemData(m_M1Block.GetCurSel());
	
	//Authentication
	iSW = Authentication(block, cKeyType, cKeyConfig, (unsigned char *)key.GetBuffer(key.GetLength()));
	key.ReleaseBuffer();
	if(SUCCESS != iSW)
	{	
		m_Status.SetWindowText("Authentication fail!");
		m_bM1CardActiveFlag = FALSE;
		return;
	}

	//WriteData
	CString writedata;
	m_M1Data.GetWindowTextEx(writedata);
	if(m_M1Data.GetTextLenEx() != 16)
	{
		MessageBox("Data length must be 16 byte",ERROR, MB_OK|MB_ICONERROR);
		m_Status.SetWindowText("Data length must be 16 byte!"); 
		return;
	}
	
	iSW = UpdataBinaryBlock(block, (unsigned char *)writedata.GetBuffer(16), 16);
	if(SUCCESS == iSW)
	{
		m_Status.SetWindowText("Write card successful!");
	}
	else
	{
		m_Status.SetWindowText("Write card fail!");
	}	
}

void CPCSCDemoDlg::OnBtM1Halt() 
{
	// TODO: Add your control notification handler code here
	int iSW;

	iSW = TypeA_Halt();
	if(SUCCESS == iSW)
	{
		m_Status.SetWindowText("Halt card successful!");
	}
	else
	{
		m_Status.SetWindowText("Halt card fail!");
	}
}
