package fr.sauveron.damien.extendedapdu;

import javacard.framework.*;
import javacardx.apdu.ExtendedLength;


public class ExtendedApplet extends Applet implements ExtendedLength
{
	final static byte RECEIVE_LONG_APDU = (byte) 0x30;
	final static byte SEND_LONG_APDU = (byte) 0x32;
	
	public byte[] ourTab;
	
	public static void install(byte[] bArray, short bOffset, byte bLength) 
	{
		new ExtendedApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
	}

	public void process(APDU apdu)
	{
		//if (apdu.isISOInterindustryCLA()) {
			if (this.selectingApplet()) {
				return;
			}// else {
			//	ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
		//	}
		//}
		
		byte[] buf = apdu.getBuffer();
		
		switch (buf[ISO7816.OFFSET_INS])
		{
		case RECEIVE_LONG_APDU:{
			short recvLen = apdu.setIncomingAndReceive();
			short LC = apdu.getIncomingLength();
							
			if (ourTab != null){
				ourTab = null;
				JCSystem.requestObjectDeletion();
			}
			ourTab = new byte[LC];
			short of = 0;
			short dataOffset = apdu.getOffsetCdata(); 
			while (recvLen > 0) {
				of = Util.arrayCopyNonAtomic(buf,dataOffset,ourTab,of,recvLen);
                		recvLen = apdu.receiveBytes(dataOffset);
			}
			break;
		}
		case SEND_LONG_APDU:{
		   	short LE = apdu.setOutgoing();
		   	short toSend = (short)ourTab.length;
		 
		   	if (LE != toSend) {
		       		apdu.setOutgoingLength(toSend);
		   	} 
		   
			   short of = 0;

			   short sentLen = (short)ourTab.length;
			   apdu.sendBytesLong(ourTab, of, sentLen);
	 
			   // while (toSend > 0) {
				// sentLen = (toSend>(short)buf.length)?(short)buf.length:toSend;       				
				// of = Util.arrayCopyNonAtomic(ourTab,of,buf,(short)0,sentLen);
		       		// apdu.sendBytes((short)0, sentLen);
		       		// toSend -= sentLen;
	  		   // }
			break;			
		}
		default:
			ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
		}
	}

}
