package zero1hd.rhythmbullet.audio.wavedecoder;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;

public class WAVSampleReader {
	private int channels;
	private double sampleRate;
	private byte[] buffer;
	private AudioInputStream audioInputStream;
	private boolean mergeChannels;
	
	public WAVSampleReader(AudioInputStream ais) throws IOException {
		audioInputStream = ais;
		buffer = new byte[audioInputStream.getFormat().getFrameSize()];
		
		channels = audioInputStream.getFormat().getChannels();
		sampleRate = audioInputStream.getFormat().getSampleRate();
	}
	
	public int getChannels() {
		return channels;
	}
	
	public double getSampleRate() {
		return sampleRate;
	}
	
	public long getFrameLength() {
		return audioInputStream.getFrameLength();
	}
	
	public int readSamplesAsFrames(float[] samples) throws IOException {
		int framesRead = 0;
		for (int sampleID = 0; sampleID < samples.length; sampleID++) {
			if (audioInputStream.read(buffer) > 0) {
				samples[sampleID] += (buffer[1] << 8) + (buffer[0] & 0x00ff);
				if (audioInputStream.getFormat().getChannels() > 1) {
					short altChan = (short) ((buffer[3] << 8) + (buffer[2] & 0x00ff));
					if (mergeChannels) {
						samples[sampleID] = altChan > samples[sampleID] ? altChan : samples[sampleID];
					} else {
						sampleID++;
						samples[sampleID] = altChan;
					}
				}
				framesRead ++;
				samples[sampleID] /= Short.MAX_VALUE+1;
			}
			
		}
		return framesRead;
	}
	
	public AudioInputStream getAudioInputStream() {
		return audioInputStream;
	}
	
	
	public void setMergeChannels(boolean mergeChannels) {
		this.mergeChannels = mergeChannels;
	}
	public boolean isMergeChannels() {
		return mergeChannels;
	}
	
}
