// MllMain.cpp : DLL アプリケーションのエントリ ポイントを定義します。
//
#include <winscard.h>
#include <stdio.h>
#include "CasProxy.h"
#include "W2L.h"
#ifndef SCARD_AUTOALLOCATE
  #define SCARD_AUTOALLOCATE (DWORD)(-1)  /**< see SCardFreeMemory() */
#endif

//////////////////////////////////////////////////////////////////////
// WinSCardフック
//////////////////////////////////////////////////////////////////////
LONG SCardConnect(SCARDCONTEXT hContext, LPCSTR szReader, DWORD dwShareMode, DWORD dwPreferredProtocols, LPSCARDHANDLE phCard, LPDWORD pdwActiveProtocol)
{
	// プロキシインスタンス生成
	CCasProxy *pCasProxy = new CCasProxy();

	// サーバに接続
	if(!pCasProxy->Connect()){
		delete pCasProxy;
		*phCard = NULL;
		return SCARD_E_READER_UNAVAILABLE;
		}

	// ハンドルに埋め込む
	*phCard = reinterpret_cast<SCARDHANDLE>(pCasProxy);
	if(pdwActiveProtocol)*pdwActiveProtocol = SCARD_PROTOCOL_T1;

	return SCARD_S_SUCCESS;
}

LONG SCardDisconnect(SCARDHANDLE hCard, DWORD dwDisposition)
{
	// サーバから切断
	CCasProxy *pCasProxy = reinterpret_cast<CCasProxy *>(hCard);
	if(pCasProxy)delete pCasProxy;

	return SCARD_S_SUCCESS;
}

LONG SCardEstablishContext(DWORD dwScope, LPCVOID pvReserved1, LPCVOID pvReserved2, LPSCARDCONTEXT phContext)
{
	return SCARD_S_SUCCESS;
}

LONG SCardFreeMemory(SCARDCONTEXT hContext, LPCVOID pvMem)
{
	return SCARD_S_SUCCESS;
}

LONG SCardListReaders(SCARDCONTEXT hContext, LPCSTR mszGroups, LPSTR mszReaders, LPDWORD pcchReaders)
{
	const char szReaderName[] = "BonCasLink Proxy Card Reader\0";

	if(pcchReaders){
		if((*pcchReaders == SCARD_AUTOALLOCATE) && mszReaders){
			*((LPCSTR *)mszReaders) = szReaderName;		
			return SCARD_S_SUCCESS;
			}
		else{
			*pcchReaders = sizeof(szReaderName);
			}
		}

	if(mszReaders) memcpy(mszReaders, szReaderName, sizeof(szReaderName));

	return SCARD_S_SUCCESS;
}

LONG SCardTransmit(SCARDHANDLE hCard, LPCSCARD_IO_REQUEST pioSendPci, LPCBYTE pbSendBuffer, DWORD cbSendLength, LPSCARD_IO_REQUEST pioRecvPci, LPBYTE pbRecvBuffer, LPDWORD pcbRecvLength)
{
	// サーバにリクエスト送受信
	CCasProxy *pCasProxy = reinterpret_cast<CCasProxy *>(hCard);
	if(!pCasProxy)return SCARD_E_READER_UNAVAILABLE;

	DWORD dwRecvLen = pCasProxy->TransmitCommand(pbSendBuffer, cbSendLength, pbRecvBuffer);
	if(pcbRecvLength)*pcbRecvLength = dwRecvLen;

	return (dwRecvLen)? SCARD_S_SUCCESS : SCARD_E_TIMEOUT;
}

LONG SCardReleaseContext(SCARDCONTEXT hContext)
{
	return SCARD_S_SUCCESS;
}

