
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.HexFormat;
import java.nio.charset.StandardCharsets;

import org._1935711.gosia.Gfx;

public class Bridge {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        byte[] demoMemory = new byte[Gfx.MEMORY_SIZE];
        byte[] rapdu = new byte[Gfx.BLOCK_LENGTH];
        short[] rapduLength = { 0 };
        byte[] apdu = new byte[5 * 2 + Gfx.BLOCK_LENGTH * 2];
        Gfx demo = new Gfx(demoMemory);

        {
            File capduFile = new File(args[0]);
            FileWriter capduFileWriter = new FileWriter(capduFile, false);
            capduFileWriter.flush();
            capduFileWriter.close();
        }

        {
            File rapduFile = new File(args[1]);
            FileWriter capduFileWriter = new FileWriter(rapduFile, false);
            capduFileWriter.flush();
            capduFileWriter.close();
        }

        try (BufferedInputStream capduReader = new BufferedInputStream(new FileInputStream(args[0]))) {
            try (PrintStream rapduPrintStream = new PrintStream(args[1])) {
                boolean headerAvailable = false;
                short lc = 0;
                while (true) {
                    if (headerAvailable == false && capduReader.available() >= 10) {
                        capduReader.read(apdu, 0, 10);
                        final String apduHeaderString = new String(apdu, 0, 10, StandardCharsets.US_ASCII);
                        final var apduHeaderHex = HexFormat.of().parseHex(apduHeaderString);
                        lc = 0;
                        headerAvailable = true;
                    }
                    if (headerAvailable == true && capduReader.available() >= (lc * 2) + 1) {
                        capduReader.read(apdu, 10, lc * 2);
                        capduReader.skip(1); // Skip new line.

                        final String apduString = new String(apdu, 0, 10 + (lc * 2), StandardCharsets.US_ASCII);

                        final var apduHex = HexFormat.of().parseHex(apduString);
                        demo.control(apduHex[1], apduHex[2], apduHex[3]);
                        for (short i = 0; i < Gfx.BLOCK_LENGTH; ++i) {
                            rapdu[i] = demo.memory[i];
                            rapduPrintStream.printf("%02X", rapdu[i]);
                        }
                        rapduPrintStream.printf("%04X\n", 0x9000);
                        headerAvailable = false;
                    }
                }
            }
        }
    }
}
