package kr.util.audio;

public class TestBeatAudioClip extends AudioClip {
	private MidiAudioClip ac;
	private int cycleBytes;
	private int durationBytes;
	private int sampleRate;
	private byte note;
	/**
	 * @param note midi note to play
	 * @param cycleTime approximate cycle time
	 * @param duration approximate duration
	 */
	public TestBeatAudioClip(int sampleRate, byte note, int cycleTime, int duration) {
		ac = new MidiAudioClip(sampleRate);
		ac.playMidi(note);
		
		this.note = note;
		this.sampleRate = sampleRate;
		this.cycleBytes = (int) ((double)cycleTime * sampleRate / 1000000);
		this.durationBytes = ac.roundToCycles((int) ((double)duration * sampleRate / 1000000), note);
	}

	@Override
	public int getNumChannels() {
		return 1;
	}

	@Override
	public int length() {
		return Integer.MAX_VALUE;
	}

	@Override
	public int getRate() {
		return sampleRate;
	}

	@Override
	public byte byteAt(int index) {
		if(index % cycleBytes < durationBytes)
		{
			return ac.byteAt(index);
		}
		return 0;
	}

	@Override
	public void copyTo(int offset, int length, byte[] dest, int destOffset) {
		//TODO: FIXME
		throw new IllegalStateException("copyTo not supported");
	}

	public int getLastBeatStart(int index) {
		return index / cycleBytes * cycleBytes;
	}

	public int getNextBeatStart(int index) {
		return (index / cycleBytes + 1) * cycleBytes;
	}
	
	
	
}
