package turgen.tapeimage;

import java.io.InputStream;
import java.io.OutputStream;
import turgen.FileFormatException;

/** Turbo (trXX) tape image chunk. These chunks are used by CASCOM
 * 
 */
public class TurboChunk implements TapeImageChunk {

    /** Chunk type*/
    private String type;
    /** Approximate baud rate*/
    private int baudRate;
    /** Chunk length*/
    private int length;
    /** Data*/
    private int[] data;

    public TurboChunk(String type) {
        this.type=type;
    }

    public int getBaudRate() {
        return baudRate;
    }


    public String getType() {
        return type;
    }

    public int getLength() {
        return length;
    }

    public int[] getData() {
        return data;
    }

    public boolean isGeneretedUsingParent() {
        return false;
    }

    public void readFromStream(InputStream s) throws Exception {
        
        /*Read length and baud rate*/
        int lengthLo = s.read();
        int lengthHi = s.read();
        int baudLo=s.read();
        int baudHi=s.read();

        if (lengthLo==-1 || lengthHi==-1 || baudLo==-1 || baudHi==-1) {
            throw new FileFormatException("Truncated "+type+" chunk header");
        }

        length = lengthLo + (256*lengthHi);
        baudRate = baudLo + (256*baudHi);

        /*Read data*/
        data = new int[length];
        for(int i=0;i<length;i++) {
            int b = s.read();
            if (b==-1) throw new FileFormatException("Truncated "+type+" chunk data");
            data[i]=b;
        }
    }

    public void writeToStream(OutputStream s) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String toString() {
        return type+": ["+Integer.toString(baudRate)+" bd] ("+Integer.toString(length)+")";
    }

    public TapeImageChunk getParent() {
        return null;
    }

}
