package org._1935711.gosia;

import org._1935711.gosia.Gfx;

import javacard.framework.ISOException;
import javacard.framework.Applet;
import javacard.framework.JCSystem;
import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.Util;

public class GosiaGfx extends Applet {
	private boolean pfailurePacket = false;
	private boolean pfailureGfx = false;
	private byte[] packetBuffer;

	Gfx gfx;

	private GosiaGfx() {
		try {
			packetBuffer = JCSystem.makeTransientByteArray(
					Gfx.MEMORY_SIZE,
					JCSystem.CLEAR_ON_RESET);
		} catch (Exception e) {
			pfailurePacket = true;
		}
		try {
			gfx = new Gfx(packetBuffer);
		} catch (Exception e) {
			pfailureGfx = true;
		}
	}

	public static void install(final byte[] bArray, final short bOffset, final byte bLength) {
		GosiaGfx applet = new GosiaGfx();
		applet.register();
	}

	public void process(APDU apdu) throws ISOException {
		if (this.selectingApplet()) {
			ISOException.throwIt(ISO7816.SW_NO_ERROR);
		} else if (!this.pfailurePacket && !pfailureGfx) {
			byte[] apduBuffer = apdu.getBuffer();
			if (apduBuffer.length >= 5) {
				short responseLengthExpected = apdu.setOutgoing();
				apdu.setOutgoingLength(Gfx.BLOCK_LENGTH);
				gfx.control(apduBuffer[1], apduBuffer[2], apduBuffer[3]);
				apdu.sendBytesLong(this.packetBuffer, (short) 0, (short) 252);
			} else {
				ISOException.throwIt((short) 0x6D00);
			}
		} else {
			ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
		}
	}
}
