const std = @import("std");
const Self = @This();

verbose: bool = false,
command__count: u64 = 0,
file__capdu: std.fs.File,
file__rapdu: std.fs.File,

// From Java source.
pub const PACKET_BUFFER_LENGTH: usize = 252;

pub fn apduTransceive(self: *Self, capdu: []const u8, rapdu: []u8, rapdu__length: usize) ![]u8 {
    var capdu__buffer: [((PACKET_BUFFER_LENGTH + 5) * 2) + 1]u8 = undefined;
    var rapdu__buffer: [((PACKET_BUFFER_LENGTH + 2) * 2) + 1]u8 = undefined;

    const capdu__string = try std.fmt.bufPrint(&capdu__buffer, "{}\n", .{std.fmt.fmtSliceHexUpper(capdu)});
    try self.file__capdu.writer().print("{s}", .{capdu__string});

    var rapdu__length__current: usize = 0;
    while (rapdu__length__current < (rapdu__length * 2) + 1) {
        rapdu__length__current += try self.file__rapdu.read(rapdu__buffer[rapdu__length__current..]);
    }
    const rapdu__ret = try std.fmt.hexToBytes(rapdu, rapdu__buffer[0 .. rapdu__length * 2]);
    if (self.verbose) {
        try std.io.getStdErr().writer().print("{d}:{}->{}.\n", .{ self.command__count, std.fmt.fmtSliceHexUpper(capdu), std.fmt.fmtSliceHexUpper(rapdu__ret) });
    }
    self.command__count += 1;
    return rapdu__ret;
}

const ControlError = error{
    RapduLengthUnexpected,
    RapduStatusUnexpected,
};
