package com.danitheskunk.skunkworks.audio.nodes;

import com.danitheskunk.skunkworks.audio.AudioBuffer;
import com.danitheskunk.skunkworks.audio.AudioEngine;
import com.danitheskunk.skunkworks.audio.ISample;

import java.util.ArrayList;
import java.util.List;

public class SamplePlayer extends Node {
	private final List<PlayingSample> samples;

	public SamplePlayer(AudioEngine engine) {
		super(engine, 0, 1);
		samples = new ArrayList<>();
	}

	@Override
	public AudioBuffer getBuffer(int slot) {
		var bufsize = getEngine().getBufferSize();
		var buf = new AudioBuffer(bufsize);
		var toRemove = new ArrayList<PlayingSample>();
		for(int i = 0; i < bufsize; ++i) {
			double l = 0;
			double r = 0;
			for(var sample : samples) {
				if(sample.loop) {
					sample.tick %= sample.sample.getLength();
				}
				if(sample.tick < sample.sample.getLength()) {
					l += sample.sample.getSampleLeft(sample.tick);
					r += sample.sample.getSampleRight(sample.tick);
					++sample.tick;
				} else {
					toRemove.add(sample);
				}
			}
			for(var sample : toRemove) {
				samples.remove(sample);
			}
			toRemove.clear();
			buf.setSample(i, l, r);
		}
		return buf;
	}

	public void play(ISample sample) {
		play(sample, false);
	}

	public void play(ISample sample, boolean looping) {
		var s = new PlayingSample();
		s.sample = sample;
		s.loop = looping;
		s.tick = 0;
		samples.add(s);
	}

	private static class PlayingSample {
		boolean loop;
		ISample sample;
		int tick;
	}
}
