package zero1hd.polyjet.ui.builders;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.FloatArray;

public class AudioGraphRelation extends Actor {
	Pixmap audioGraph;
	Texture textureOfGraph;
	FloatArray mainGraph;
	FloatArray overlayGraph;
	int audioDataIndex;
	
	public AudioGraphRelation(FloatArray mainGraph, FloatArray overlayGraph, int graphSizeW, int graphSizeH) {
		audioGraph = new Pixmap(graphSizeW, graphSizeH, Format.RGBA8888);
		audioGraph.setColor(0.1f, 0.1f, 0.1f, 0.75f);
		audioGraph.fill();
		
		textureOfGraph = new Texture(audioGraph);
		setWidth(Gdx.graphics.getWidth());
		setHeight(280);
		this.mainGraph = mainGraph;
		this.overlayGraph = overlayGraph;
	}
	
	public void setAudioDataIndex(int audioDataIndex) {
		this.audioDataIndex = audioDataIndex;
	}
	
	float scale = 0.2f;
	@Override
	public void act(float delta) {
		audioGraph.setColor(0f, 0f, 0f, 0.75f);
		audioGraph.fill();
		
		if (Gdx.input.isKeyPressed(Keys.COMMA)) {
			if (scale > 0.02) {
				scale -= 0.005f;
			}
		} else if (Gdx.input.isKeyPressed(Keys.PERIOD)) {
			if (scale < 1) {
				scale += 0.005f;
			}
		}
		
		audioGraph.setColor(0f, 1f, 1f, 0.75f);
		for (int x = 0; x < audioGraph.getWidth() -1; x++) {
			try {
				audioGraph.drawLine(x, (int) (audioGraph.getHeight()-mainGraph.get(audioDataIndex+x-audioGraph.getWidth()/2)*scale), x+1, (int) (audioGraph.getHeight()-mainGraph.get(audioDataIndex+x+1-audioGraph.getWidth()/2)*scale));
			} catch (IndexOutOfBoundsException e) {
				
			}
		}
		
		audioGraph.setColor(0f, 0.25f, 1f, 0.75f);
		for (int x = 0; x < audioGraph.getWidth() -1; x++) {
			try {
				audioGraph.drawLine(x, (int) (audioGraph.getHeight()-overlayGraph.get(audioDataIndex+x-audioGraph.getWidth()/2)*scale), x+1, (int) (audioGraph.getHeight()-overlayGraph.get(audioDataIndex+x+1-audioGraph.getWidth()/2)*scale));
			} catch (IndexOutOfBoundsException e) {
				
			}
		}
		
		audioGraph.setColor(0f, 0f, 1, 0.95f);
		audioGraph.drawLine(audioGraph.getWidth()/2, 0, audioGraph.getWidth()/2, audioGraph.getHeight());
		
		textureOfGraph.draw(audioGraph, 0, 0);
		super.act(delta);
	}
	
	@Override
	public void draw(Batch batch, float parentAlpha) {
		batch.draw(textureOfGraph, getX(), getY(), getWidth(), getHeight());
		super.draw(batch, parentAlpha);
	}
	
}
