package turgen.tapeimage;

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


public class DataChunk implements TapeImageChunk{

    /**Chunk type*/
    private static final String type = "data";
    /**Chunk length*/
    private int length;
    /**Chunk AUX*/
    private int aux;
    /**Chunk data*/
    private int[] data;
    /**Parent chunk*/
    private TapeImageChunk parent;

    public DataChunk(TapeImageChunk parent) {
        this.parent=parent;
    }

    public int getAux() {
        return aux;
    }

    public String getType() {
        return type;
    }

    public int getLength() {
        return length;
    }

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

    public boolean isGeneretedUsingParent() {
        return true;
    }

    public void readFromStream(InputStream s) throws Exception {

        /*Read length and baud rate*/
        int lengthLo = s.read();
        int lengthHi = s.read();
        int auxLo=s.read();
        int auxHi=s.read();

        if (lengthLo==-1 || lengthHi==-1 || auxLo==-1 || auxHi==-1) {
            throw new FileFormatException("Truncated data chunk header");
        }

        length = lengthLo + (256*lengthHi);
        aux = auxLo + (256*auxHi);

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

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

    public String toString() {
        return "data: ["+Integer.toString(aux)+"] ("+Integer.toString(length)+")";
    }

    public TapeImageChunk getParent() {
        return parent;
    }

}
