package speiger.src.coreengine.rendering.shaderOld.uniforms;

import java.util.Objects;

import org.lwjgl.opengl.GL20;

import speiger.src.coreengine.rendering.shaderOld.ShaderProgram;

public class UniformArrayBase<T extends Object> extends Uniform {
	protected int[] positions;
	protected boolean[] first;
	protected Object[] lastValues;
	protected int limit;

	public UniformArrayBase(String id, int length) {
		super(id);
		limit = length;
		positions = new int[length];
		first = new boolean[length];
		lastValues = new Object[length];
	}

	public int getPosition(int index) {
		return positions[index];
	}

	@SuppressWarnings("unchecked")
	protected boolean hasChanged(int index, T value) {
		if (!first[index] || !Objects.equals(lastValues[index], value)) {
			first[index] = true;
			lastValues[index] = setValue((T)lastValues[index], value);
			return true;
		}
		return false;
	}

	protected T setValue(T oldValue, T newValue) {
		return newValue;
	}

	@Override
	public void loadUniform(ShaderProgram prog) {
		for (int i = 0; i < positions.length; i++) {
			String realName = name + "[" + i + "]";
			positions[i] = GL20.glGetUniformLocation(prog.getShaderID(), realName);
			if (positions[i] == -1)
				System.err.println("Couldn't find Shader Uniform: " + realName + ", Shader ID: " + prog.getShaderID());
		}
	}

}
