package zero1hd.polyjet.audio;

import java.io.IOException;
import java.security.InvalidParameterException;

import javax.sound.sampled.AudioFormat;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.files.FileHandle;

import zero1hd.wavedecoder.WavDecoder;

public class WavAudioData implements AudioData {
	private int readWindowSize = 1024;
	private AudioFormat format;
	int readIndex;
	Music playbackMusic;
	WavDecoder decoder;
	
	public WavAudioData(FileHandle file) {
		reset();
		try {
			decoder = new WavDecoder(file);
			decoder.initDataStream();
			decoder.getHeaderInfo();
		} catch (InvalidParameterException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		playbackMusic = Gdx.audio.newMusic(file);
		format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, (float) decoder.getSampleRate(), 16, decoder.getChannels(), decoder.getChannels()*2, (float) decoder.getSampleRate(), false);
	}
	
	@Override
	public void readIndexUpdate() {
		readIndex = (int) (playbackMusic.getPosition() * decoder.getSampleRate() / readWindowSize);
	}
	
	@Override
	public int getReadIndex() {
		return readIndex;
	}
	
	@Override
	public void reset() {
		if (playbackMusic != null) {
			playbackMusic.stop();
			playbackMusic.dispose();
			playbackMusic = null;
		}
	}
	
	@Override
	public int getReadWindowSize() {
		return readWindowSize;
	}
	
	@Override
	public Music getPlaybackMusic() {
		return playbackMusic;
	}

	@Override
	public int readSamples(float[] samples) {
		return decoder.readSamples(samples);
	}

	@Override
	public AudioFormat getFormat() {
		return format;
	}

	@Override
	public int getSampleCount() {
		return decoder.getDataSize()/(2*decoder.getChannels());
	}
}
