/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CardConnect;

import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;

public class APDU {
    private SendData rawDataSender;
    private byte cla;
    
    public APDU(byte[] aid, byte cla) {
        this.rawDataSender = new SendData();
        this.cla = cla;
        
        ResponseAPDU response = SendAPDU((byte)0x00, (byte)0xA4, (byte)0x04, (byte)0x00, (byte)aid.length, aid, (byte)0x00);

    }
    
    public ResponseAPDU SendApdu(byte[] raw) {
        return this.rawDataSender.SendRawData(raw);
    }
    
    public ResponseAPDU SendApdu(byte instruction, byte[] payload, byte expectedResponsePayloadSize) {
        return SendAPDU(this.cla, instruction, (byte) 0x00, (byte) 0x00, (byte)payload.length, payload, expectedResponsePayloadSize);
    }
    
    public ResponseAPDU SendApdu(CommandAPDU command) {
        return this.rawDataSender.SendRawData(command);
    }
    
    public ResponseAPDU SendAPDU(byte cla, byte instruction, byte p1,
            byte p2, byte payloadSize,  byte[] payload, byte expectedResponsePayloadSize) {
        int apduSize = 5 + payload.length;
        if (expectedResponsePayloadSize > 0) {
            apduSize++;
        }
        byte[] apduCommand = new byte[apduSize];
        apduCommand[0] = cla;
        apduCommand[1] = instruction;
        apduCommand[2] = p1;
        apduCommand[3] = p2;
        //if (pa)
        apduCommand[4] = payloadSize;
        for (int i = 0; i < payloadSize; ++i) {
            apduCommand[5+i] = payload[i];
        }
        if (expectedResponsePayloadSize > 0) {
            apduCommand[5+payloadSize] = expectedResponsePayloadSize;
        }
        return this.rawDataSender.SendRawData(apduCommand);
    }
}
