package com.danitheskunk.skunkworks.audio.nodes;

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

public class Mixer extends Node {
	private final int channels;

	public Mixer(AudioEngine engine, int channels) {
		super(engine, channels, 1);
		this.channels = channels;
	}

	@Override
	public AudioBuffer getBuffer(int slot) {
		var bufs = new AudioBuffer[channels];
		var bufferSize = getEngine().getBufferSize();
		var buf = new AudioBuffer(bufferSize);

		for(int channel = 0; channel < channels; ++channel) {
			bufs[channel] = getBufferFromInput(channel);
		}

		for(int i = 0; i < bufferSize; ++i) {
			double l = 0.0;
			double r = 0.0;
			for(var inBuf : bufs) {
				if(inBuf != null) {
					l += inBuf.getLeft(i);
					r += inBuf.getRight(i);
				}
			}
			//todo: dividing by channels just temporary mess
			buf.setSample(i, l / channels, r / channels);
		}
		return buf;
	}
}
