/*
 * 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 com.cloudsoft.MastercardFileReader;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;

/**
 *
 * @author Lisewski
 */
public class IPMInputStream {

    private final FileInputStream fis;
    private ByteArrayInputStream bais;
    private final int blockSize = 1012;
    private final char blockChar = 0x40;
    private final byte[] ba = new byte[blockSize];
    private int bytesLeft = 0;
    private boolean lastBlock = false;

    public IPMInputStream(String fileName) throws Exception {
        fis = new FileInputStream(fileName);
    }

    public byte[] readNBytes(int bytes) throws Exception {
        byte[] tmp = new byte[bytes];
        int bytesRead = 0;
        if (bytesLeft < bytes) {
            // Read part of the bytes then get a new block
            if (bytesLeft > 0) {
                bais.read(tmp, 0, bytesLeft);
                bytesRead = bytesLeft;
            }
            readBlock();
        }
        if (bytesRead < bytes) {
            bais.read(tmp, bytesRead, bytes - bytesRead);
            bytesLeft -= bytes - bytesRead;
        }
        return tmp;
    }

    public boolean lastBlock() {
        return lastBlock;
    }

    private void readBlock() throws Exception {
        bytesLeft = fis.read(ba, 0, blockSize);
//        System.out.println("bytesLeft : " + bytesLeft);
//        bytesLeft = ba.length;
        bais = new ByteArrayInputStream(ba);
        if (bytesLeft == blockSize) {
            // Read Padding
            byte[] padding = new byte[2];
            fis.read(padding, 0, 2);
            if (padding[0] != blockChar || padding[1] != blockChar) {
                System.out.println(String.format("Padding contains wrong characters %02X%02X. Expected %H%H", blockChar & 0xFF, blockChar & 0xFF, padding[0] & 0xFF, padding[1] & 0xFF));
            }
        } else {
            lastBlock = true;
        }
    }

}
