package applet;

import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.Util;

public class LinearEFile extends EFile {
    protected Record[] records;
    protected byte currRecordNum;
    private final short recordLength;

    public LinearEFile(short fileID, byte[] FCP, byte numOfRecordsLimit, short recordLength) {
        super(fileID, FCP);
        this.records = new Record[numOfRecordsLimit];
        this.currRecordNum = 0;
        this.recordLength = recordLength;
        for(short i = 0; i < (short) numOfRecordsLimit; i++) {
            this.addRecord(new byte[recordLength]);
        }
    }

    public byte getCurrentRecordNum() {
        return this.currRecordNum;
    }

    public short getRecordLength() {
        return this.recordLength;
    }

    public void addRecord(byte[] record) {
        if(records.length == currRecordNum) {
            // 6A84: There is insufficient memory space in record or file
            ISOException.throwIt(ISO7816.SW_FILE_FULL);
        }
        if(record.length == recordLength) {
            records[currRecordNum++] = new Record(record);
        }
    }

    public byte[] getRecord (byte recordIdx) {
        if((recordIdx < 0) || (recordIdx > currRecordNum)) {
            return null;
        }
        return this.records[recordIdx].data;
    }

    void clear() {
        for(short i = 0; i < currRecordNum; i++) {
            Util.arrayFillNonAtomic(records[i].data, (short)0, (short)records[i].data.length, (byte)0);
            records[i] = null;
        }
    }

}
