package zero1hd.rhythmbullet.audio.wavedecoder;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

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

public class WavDecoder {
	private FileHandle file;
	
	private int channels;
	private double sampleRate;
	private String fileName;
	private byte[] buffer;
	private AudioInputStream audioInputStream;
	
	public WavDecoder(FileHandle file) throws IOException {
		this.file = file;
		try {
			audioInputStream = AudioSystem.getAudioInputStream(file.file());
			Gdx.app.debug("WAVDecoder", String.valueOf(audioInputStream.getFormat().getFrameSize()));
			buffer = new byte[audioInputStream.getFormat().getFrameSize()];
			
			channels = audioInputStream.getFormat().getChannels();
			sampleRate = audioInputStream.getFormat().getSampleRate();
			fileName = file.name();
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		}
	}
	
	public int getChannels() {
		return channels;
	}
	
	public double getSampleRate() {
		return sampleRate;
	}
	
	public float getDurationInSeconds() {
		return audioInputStream.getFrameLength()/audioInputStream.getFormat().getFrameRate();
	}
	
	public long getFrameLength() {
		return audioInputStream.getFrameLength();
	}
	
	public String getFileName() {
		return fileName;
	}
	
	public FileHandle getFile() {
		return file;
	}
	
	public int readSamples(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) {
					samples[sampleID] += (buffer[3] << 8) + (buffer[2] & 0x00ff);
					samples[sampleID] /= 2;
				}
				framesRead ++;
				
				samples[sampleID] /= Short.MAX_VALUE+1;
			}
			
		}
		
		return framesRead;
	}
	
	public void cleanAndClose() {
		try {
			audioInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
