/*
    $Id: pcsc_handle.c,v 1.14 2004/02/22 02:33:52 toni Exp $
    Copyright (c) 2001 - 2004 Toni Andjelkovic <toni@soth.at>.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <pcsc_ruby.h>

void Init_PCSC_Handle(void)
{
    cPCSC_Handle = rb_define_class_under(mPCSC, "Handle", rb_cObject);
    rb_define_singleton_method(cPCSC_Handle, "new", PCSC_Handle_new, -1);
    rb_define_method(cPCSC_Handle, "initialize", PCSC_Handle_init, 0);
    rb_define_method(cPCSC_Handle, "Connect", PCSC_Handle_Connect, -1);
    rb_define_method(cPCSC_Handle, "Disconnect", PCSC_Handle_Disconnect, -1);
    rb_define_method(cPCSC_Handle, "Reconnect", PCSC_Handle_Reconnect, -1);
    rb_define_method(cPCSC_Handle, "BeginTransaction", PCSC_Handle_BeginTransaction, 0);
    rb_define_method(cPCSC_Handle, "EndTransaction", PCSC_Handle_EndTransaction, -1);
    rb_define_method(cPCSC_Handle, "CancelTransaction", PCSC_Handle_CancelTransaction, 0);
    rb_define_method(cPCSC_Handle, "Control", PCSC_Handle_Control, -1);
    rb_define_method(cPCSC_Handle, "SetTimeout", PCSC_Handle_SetTimeout, -1);
    rb_define_method(cPCSC_Handle, "Status", PCSC_Handle_Status, 0);
    rb_define_method(cPCSC_Handle, "Transmit", PCSC_Handle_Transmit, -1);
}

VALUE PCSC_Handle_new(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;

    self = Data_Make_Struct(cPCSC_Handle, SCARDHANDLE, NULL, PCSC_Handle_free, handle);
    rb_obj_call_init(self, argc, argv);
    return self;
}

VALUE PCSC_Handle_init(VALUE self)
{
    SCARDHANDLE *handle;

    Data_Get_Struct(self, SCARDCONTEXT, handle);
    return self;
}

VALUE PCSC_Handle_Connect(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    SCARDCONTEXT *ctx;
    long rv;
    VALUE ctx_obj, szReader, dwShareMode, dwPreferredProtocols;
    unsigned long pwdActiveProtocol;

    if (argc != 4)
        rb_raise(rb_eArgError, "wrong number of arguments (need 4, got %d)", argc);
    Check_Type(ctx_obj = argv[0], T_DATA);
    Check_Type(szReader = argv[1], T_STRING);
    if ((TYPE(argv[2]) != T_FIXNUM) && (TYPE(argv[2]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwShareMode = argv[2];
    if ((TYPE(argv[3]) != T_FIXNUM) && (TYPE(argv[3]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwPreferredProtocols = argv[3];
    Data_Get_Struct(self, SCARDHANDLE, handle);
    Data_Get_Struct(ctx_obj, SCARDCONTEXT, ctx);
    rv = SCardConnect(*ctx, STR2CSTR(szReader), NUM2ULONG(dwShareMode), NUM2ULONG(dwPreferredProtocols), handle, &pwdActiveProtocol);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardConnect: %s", pcsc_stringify_error(rv));
    return UINT2NUM(pwdActiveProtocol);
}

VALUE PCSC_Handle_Disconnect(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    long rv;
    unsigned long dwDisposition;

    if (argc != 1)
        rb_raise(rb_eArgError, "wrong number of arguments (need 1, got %d)", argc);
    if ((TYPE(argv[0]) != T_FIXNUM) && (TYPE(argv[0]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwDisposition = argv[0];
    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardDisconnect(*handle, NUM2ULONG(dwDisposition));
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardDisconnect: %s", pcsc_stringify_error(rv));
    return self;
}

VALUE PCSC_Handle_Reconnect(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    long rv;
    VALUE dwShareMode, dwPreferredProtocols, dwInitialization;
    unsigned long pwdActiveProtocol;

    if (argc != 3)
        rb_raise(rb_eArgError, "wrong number of arguments (need 3, got %d)", argc);
    if ((TYPE(argv[0]) != T_FIXNUM) && (TYPE(argv[0]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwShareMode = argv[0];
    if ((TYPE(argv[1]) != T_FIXNUM) && (TYPE(argv[1]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwPreferredProtocols = argv[1];
    if ((TYPE(argv[2]) != T_FIXNUM) && (TYPE(argv[2]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwInitialization = argv[2];
    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardReconnect(*handle, NUM2ULONG(dwShareMode), NUM2ULONG(dwPreferredProtocols), NUM2ULONG(dwInitialization), &pwdActiveProtocol);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardReconnect: %s", pcsc_stringify_error(rv));
    return UINT2NUM(pwdActiveProtocol);
}

VALUE PCSC_Handle_BeginTransaction(VALUE self)
{
    SCARDHANDLE *handle;
    long rv;

    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardBeginTransaction(*handle);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardBeginTransaction: %s", pcsc_stringify_error(rv));
    return self;
}

VALUE PCSC_Handle_EndTransaction(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    long rv;
    VALUE dwDisposition;

    if (argc != 1)
        rb_raise(rb_eArgError, "wrong number of arguments (need 1, got %d)", argc);
    if ((TYPE(argv[0]) != T_FIXNUM) && (TYPE(argv[0]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    dwDisposition = argv[0];
    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardEndTransaction(*handle, NUM2ULONG(dwDisposition));
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardEndTransaction: %s", pcsc_stringify_error(rv));
    return self;
}

VALUE PCSC_Handle_Control(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    long rv;
    VALUE pbSendBuffer, retval;
    char *pbRecvBuffer;
    unsigned long pcbRecvLength;

    if (argc != 1)
        rb_raise(rb_eArgError, "wrong number of arguments (need 1, got %d)", argc);
    Check_Type(pbSendBuffer = argv[0], T_STRING);
    Data_Get_Struct(self, SCARDHANDLE, handle);
    /* printf("len of str: %lu\n", RSTRING(pbSendBuffer)->len); */
    /* alloc a string temporarily */
    pbRecvBuffer = ALLOC_N(char, PCSCLITE_MAX_MESSAGE_SIZE);
    rv = SCardControl(*handle, RSTRING(pbSendBuffer)->ptr, RSTRING(pbSendBuffer)->len, pbRecvBuffer, &pcbRecvLength);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardControl: %s", pcsc_stringify_error(rv));
    retval = rb_tainted_str_new(pbRecvBuffer, (long) pcbRecvLength);
    xfree(pbRecvBuffer);
    return retval;
}

VALUE PCSC_Handle_CancelTransaction(VALUE self)
{
    SCARDHANDLE *handle;
    long rv;

    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardCancelTransaction(*handle);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardCancelTransaction: %s", pcsc_stringify_error(rv));
    return self;
}

VALUE PCSC_Handle_SetTimeout(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    long rv;

    if (argc != 1)
        rb_raise(rb_eArgError, "wrong number of arguments (need 1, got %d)", argc);
    
    if ((TYPE(argv[0]) != T_FIXNUM) && (TYPE(argv[0]) != T_BIGNUM))
        rb_raise(rb_eTypeError, "wrong type of argument");
    Data_Get_Struct(self, SCARDHANDLE, handle);
    rv = SCardSetTimeout(*handle, NUM2ULONG(argv[0]));
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardSetTimeout: %s", pcsc_stringify_error(rv));
    return self;
}

VALUE PCSC_Handle_Status(VALUE self)
{
    SCARDHANDLE *handle;
    long rv;
    VALUE ary = rb_ary_new();
    char *szReaderName, *pbAtr;
    unsigned long pdwState, pdwProtocol;
    unsigned long pcbAtrLen = MAX_ATR_SIZE;
    unsigned long pcchReaderLen = MAX_READERNAME; /* fixed bufsize */

    Data_Get_Struct(self, SCARDHANDLE, handle);
    szReaderName = ALLOC_N(char, pcchReaderLen);
    pbAtr = ALLOC_N(char, MAX_ATR_SIZE);
    rv = SCardStatus(*handle, szReaderName, &pcchReaderLen, &pdwState, &pdwProtocol, pbAtr, &pcbAtrLen);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardStatus: %s %ul", pcsc_stringify_error(rv), pcchReaderLen);
    rb_ary_push(ary, UINT2NUM(pdwState));
    rb_ary_push(ary, rb_tainted_str_new2(szReaderName));
    rb_ary_push(ary, UINT2NUM(pdwProtocol));
    rb_ary_push(ary, rb_tainted_str_new(pbAtr, (long) pcbAtrLen));
    xfree(szReaderName);
    xfree(pbAtr);
    return ary;
}

VALUE PCSC_Handle_Transmit(int argc, VALUE *argv, VALUE self)
{
    SCARDHANDLE *handle;
    SCARD_IO_REQUEST *pioSendPci, *pioRecvPci;
    long rv;
    VALUE SendPci, pbSendBuffer;
    char *pbRecvBuffer;
    unsigned long pcbRecvLength = PCSCLITE_MAX_MESSAGE_SIZE;
    VALUE ary = rb_ary_new();

    if (argc != 2)
        rb_raise(rb_eArgError, "wrong number of arguments (need 2, got %d)", argc);
    Check_Type(SendPci = argv[0], T_DATA);
    Check_Type(pbSendBuffer = argv[1], T_STRING);
    Data_Get_Struct(self, SCARDHANDLE, handle);
    Data_Get_Struct(SendPci, SCARD_IO_REQUEST, pioSendPci);
    pioRecvPci = ALLOC(SCARD_IO_REQUEST);
    MEMZERO(pioRecvPci, SCARD_IO_REQUEST, 1);
    pbRecvBuffer = ALLOC_N(char, PCSCLITE_MAX_MESSAGE_SIZE);
    rv = SCardTransmit(*handle, pioSendPci, STR2CSTR(pbSendBuffer), (unsigned long) RSTRING(pbSendBuffer)->len, pioRecvPci, pbRecvBuffer, &pcbRecvLength);
    if (rv != SCARD_S_SUCCESS)
        rb_raise(rb_eRuntimeError, "SCardTransmit: %s", pcsc_stringify_error(rv));
    rb_ary_push(ary, rb_tainted_str_new(pbRecvBuffer, (long) pcbRecvLength));
    rb_ary_push(ary, Data_Wrap_Struct(cPCSC_IORequest, NULL, PCSC_IORequest_free, pioRecvPci));
    xfree(pbRecvBuffer);
    /*  pioRecvPci will be free'd by the GC
        via the free function pointer in Data_Wrap_Struct */
    return ary;
}

void PCSC_Handle_free(SCARDHANDLE *handle)
{
    if (handle)
        xfree(handle);
}
