import java.io.IOException;
import java.util.Arrays;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.UGen;
import net.beadsproject.beads.data.AudioFile;
import net.beadsproject.beads.data.Sample;

public class BufferedSampleTest {

	static class BufferedSamplePlayer extends UGen
	{
		Sample bs;
		int frame = 0;
		
		// read one frame at a time from sample? or a whole chunk?
		static final boolean PERFRAME = true; 
		
		public BufferedSamplePlayer(AudioContext ac, Sample bs)
		{
			super(ac,bs.getNumChannels());
			this.bs = bs;			
		}
		
		@Override
		public void calculateBuffer()
		{
			long nFrames = bs.getNumFrames();
			if (nFrames==AudioSystem.NOT_SPECIFIED)
			{
				System.out.println("dude it's an error");
				return;				
			}
			
			if (frame < nFrames)
			{
				if (PERFRAME)
				{
					int from = frame;
					int i = 0;
					int to = (int) Math.min(nFrames,frame+bufferSize);
					float[] data = new float[outs];
					for(;from<to;++from,++i)
					{
						bs.getFrame(from, data);
						for(int ch=0;ch<outs;ch++)
						{
							bufOut[ch][i] = data[ch];
						}
					}
				}
				else
				{				
					bs.getFrames(frame, bufOut);
				}
			}
			
			if ((nFrames - frame) < this.bufferSize)
			{
				for(int ch = 0;ch<this.outs;ch++)
					Arrays.fill(bufOut[ch], (int)(nFrames - frame), this.bufferSize, 0);					
				pause(true);
			}
			else
			{			
				frame += bufOut[0].length;
			}			
		}
	}
	
	/**
	 * @param args
	 * @throws UnsupportedAudioFileException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException, UnsupportedAudioFileException {
		AudioContext ac = new AudioContext();

		// Set the regime..
		int ms = 1000;
		Sample.Regime regime = new Sample.TimedRegime(ms,ms*5,0,ms*10,Sample.TimedRegime.Order.ORDERED);
		
		String filename = "audio/gammaBrosTheme.mp3";
		//String filename = "audio/1234.aif";
		//bs.setFile("audio/1234.aif");
		//bs.setFile("audio/tada.wav");
		// create an audiofile then input it into the sample
		// note, we don't have to create an AudioFile explicitly
		// but I am doing it for debugging purposes..
		AudioFile af = new AudioFile(filename);

		Sample bs = new Sample(af, regime);
		System.out.println(af.info());
		
		//System.exit(1);
		BufferedSamplePlayer bsp = new BufferedSamplePlayer(ac,bs);
		ac.out.addInput(bsp);
		ac.start();		
	}

}
