#!/usr/local/bin/ruby
require "PCSC"
include PCSC

puts "module version: %s" % PCSC_RUBY_VERSION

puts "Reader config: %s" % PCSCLITE_READER_CONFIG

# memory leak test
#while true
    ctx = Context.new(SCARD_SCOPE_SYSTEM)
    ctx.SetTimeout(20)
    puts "Readers: %s" % ctx.ListReaders.inspect
    puts "Reader Groups: %s" % ctx.ListReaderGroups.inspect

    state = ReaderState.new
    state.Reader = ctx.ListReaders[0]
    state.CurrentState = SCARD_STATE_EMPTY
    puts "waiting 10 sec for card insertion ..."
    ctx.GetStatusChange(10000, [ state ])

    handle = Handle.new
    proto = handle.Connect(ctx, ctx.ListReaders[0], SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0)
    puts "Connected, proto: %d\n" % proto

    #handle.SetTimeout(20)
    #puts "SetTimeout: 20"

    puts "Status: %s" % handle.Status.inspect
    puts "ATR: %s" % hexify(handle.Status[3])

    handle.BeginTransaction
    puts "BeginTransaction"

    puts "SCARD_PCI_T0.Protocol: %u" % SCARD_PCI_T0.Protocol
    puts "SCARD_PCI_T1.Protocol: %u" % SCARD_PCI_T1.Protocol
    puts "SCARD_PCI_RAW.Protocol: %u" % SCARD_PCI_RAW.Protocol

    result = handle.Transmit(SCARD_PCI_T0, "\xF0\x2A\x00\x01\x08\x2C\x15\xE5\x26\xE9\x3E\x8A\x19")
    puts "Result: %s (%s)" % [ hexify(result[0]), result[0].inspect ]
    puts "Result IORequest.Protocol: %u" % result[1].Protocol

    handle.CancelTransaction
    puts "CancelTransaction"

    handle.EndTransaction(SCARD_LEAVE_CARD)
    puts "EndTransaction"

    handle.Disconnect(SCARD_RESET_CARD)
    puts "Disconnected"

    ctx.ReleaseContext
    ctx.Unload
    GC.start
    sleep 0.5
#end

