package zero1hd.rhythmbullet.audio.visualizer;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.MathUtils;

import zero1hd.rhythmbullet.audio.MusicDataPack;

public class HorizontalVisualizer extends VisualizerCore {
	private Pixmap pixmap;
	private Texture bar;
	private int barWidth;
	private int binsPerBar;
	private int spaceBetweenBars;
	private int[] barHeights;
	private int smoothRange;
	private float barHeightMultiplier;
	public HorizontalVisualizer() {
		super(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/2, 0, 0);
		barHeightMultiplier = Gdx.graphics.getHeight()*0.01f;
		pixmap = new Pixmap(2, 2, Format.RGBA8888);
		pixmap.setColor(Color.GRAY);
		pixmap.fill();
		bar = new Texture(pixmap);
		pixmap.dispose();
		barCount = 70;
		barWidth = MathUtils.ceil((float) width/(float) barCount);
		spaceBetweenBars = (barWidth-2);
		barWidth -= spaceBetweenBars;
		smoothRange = 4;
		barHeights = new int[barCount];
	}
	
	@Override
	public void render(Batch batch, float parentAlpha) {
		if (cmi != null) {
			for (int i = 0; i < barCount; i++) {
				barHeights[i] = 0;
				for (int j = 0; j < binsPerBar; j++) {
					barHeights[i] += Math.abs(audioPCM[j+i*binsPerBar]);
				}
				barHeights[i] /= binsPerBar;
				barHeights[i] *= barHeightMultiplier;
			}
			
			for (int i = 0; i < barCount; i++) {
				int avg = 0;
				for (int range = 0; range < smoothRange; range++) {
					if (i+range < barCount) {
						avg += barHeights[i+range];
					}
					if (i-range >= 0) {
						avg += barHeights[i-range];
					}
					
				}
				barHeights[i] = avg/(smoothRange*2);
				batch.draw(bar, xPos + i*(barWidth+spaceBetweenBars), yPos, barWidth, barHeights[i]);
			}
		}
		super.render(batch, parentAlpha);
	}
	
	@Override
	public void setMDP(MusicDataPack mdp) {
		super.setMDP(mdp);
		float validBins = (5000/((mdp.getSampleRate()/2)/((audioPCM.length/2)+1)));
		Gdx.app.debug("Visualizer", "valid frequency bins " + validBins);
		binsPerBar = MathUtils.round((validBins/barCount));
	}
	
	@Override
	public void dispose() {
		bar.dispose();
		super.dispose();
	}
}
