package turgen.tapeimage;

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


public class UnknownChunk implements TapeImageChunk {

    private String type;
    private int length;
    private int[] data;
    private int aux;

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

    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 aux*/
        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 "+type+" 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 "+type+" chunk data");
            data[i]=b;
        }
    }

    public void writeToStream(java.io.DataOutputStream s) throws Exception {
        s.writeBytes(type);
        s.write(length%256);
        s.write(length/256);
        s.write(aux%256);
        s.write(aux/256);
        for(int i=0;i<data.length;i++) {
            s.write(data[i]);
        }
    }

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

    public TapeImageChunk getParent() {
        return null;
    }

}
