#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winscard.h>
#include "ACS38DrvTools.h"
#include "ACR38IOCtrl.h"

LONG
ACS38DrvSetCardType(
		SCARDCONTEXT		scardContext,
		const char*			readerName,
		ACS38DRV_CARD_TYPE	cardType)
{
	SCARDHANDLE					scardHandle;
	DWORD						activeProtocol;
	ACR38_IO_CTRL				ioCtrl;
	SCARD_IO_REQUEST			ioRecvPci;
	char						recvBuf[10];
	DWORD						recvBufLen = 10;
	LONG						rv;

	rv = SCardConnect(	scardContext,
						readerName,
						SCARD_SHARE_DIRECT,
						SCARD_PROTOCOL_RAW,
						&scardHandle,
						&activeProtocol);
	if (rv != SCARD_S_SUCCESS)
	{
		goto SCardConnectFailed;
	}

	ioCtrl.type	= ACR38_IO_CTRL_SET_CARD_TYPE;
	switch (cardType)
	{
	case ACS38DRV_CARD_TYPE_MCU:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_MCU;
		break;

	case ACS38DRV_CARD_TYPE_1K_16K:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_1K_16K;
		break;

	case ACS38DRV_CARD_TYPE_32K_1024K:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_32K_1024K;
		break;

	case ACS38DRV_CARD_TYPE_AT88SC153:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_AT88SC153;
		break;

	case ACS38DRV_CARD_TYPE_AT88SC1608:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_AT88SC1608;
		break;

	case ACS38DRV_CARD_TYPE_SLE4418_4428:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_SLE4418_4428;
		break;

	case ACS38DRV_CARD_TYPE_SLE4432_4442:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_SLE4432_4442;
		break;

	case ACS38DRV_CARD_TYPE_MCU_T0:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_MCU_T0;
		break;

	case ACS38DRV_CARD_TYPE_MCU_T1:
		ioCtrl.setCardTypeData.type	= READER_CARD_TYPE_MCU_T1;
		break;

	default:
		goto UnknownCardType;
	}
	rv = SCardTransmit(	scardHandle,
						SCARD_PCI_RAW,
						(LPCBYTE)&ioCtrl,
						sizeof(ACR38_IO_CTRL),
						&ioRecvPci,
						recvBuf,
						&recvBufLen);
	if (rv != SCARD_S_SUCCESS)
	{
		goto SCardTransmitFailed;
	}

	(void)SCardDisconnect(scardHandle, SCARD_RESET_CARD);
	return SCARD_S_SUCCESS;

/****** Error Part ******/
SCardTransmitFailed:
UnknownCardType:
	(void)SCardDisconnect(scardHandle, SCARD_RESET_CARD);

SCardConnectFailed:
	return rv;
}
