package turgen.tapeimage;

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


public class PWMChunk implements TapeImageChunk{

    /**Chunk type*/
    private final String type;
    /**Chunk length*/
    private int length;
    /**Chunk data*/
    private int[] data;
    /**Parent chunk*/
    private final TapeImageChunk parent;
    /**Aux bytes*/
    private int auxLo;
    private int auxHi;
    private int aux;
    
    public PWMChunk(String type,TapeImageChunk parent) {
        
        this.type=type;
        this.parent=parent;
    }

 
    public String getType() {
        return type;
    }

    public int getLength() {
        return length;
    }

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

    public boolean isGeneretedUsingParent() {
        return false;
    }
    
    public int getAux() {
        return aux;
    }
    
    public int getAuxLo() {
        return auxLo;
    }
    
    public int getAuxHi() {
        return auxHi;
    }

    public void readFromStream(InputStream s) throws Exception {

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

        if (lengthLo==-1 || lengthHi==-1 || auxLo==-1 || auxHi==-1) {
            throw new FileFormatException("Truncated pwmX 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 pwmX 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(length)+")";
    }

    public TapeImageChunk getParent() {
        return parent;
    }

}
