package net.dzzd.extension.jogl;

import javax.media.opengl.*;
import javax.media.opengl.glu.*;
import javax.media.opengl.GL;


public class JOGLShaderProgram
{	
	private int programId;
	private GL gl;
	private GLU glu=new GLU();
	private JOGLShader vertexShader;
	private JOGLShader fragmentShader;
	private boolean compiled;
	
	
		
	public JOGLShaderProgram(GL gl)
	{
		this.programId=-1;
		this.vertexShader=null;
		this.fragmentShader=null;
		this.compiled=false;
		this.gl=gl;
	}
	
	public void setVertexShader(JOGLShader vertexShader)
	{
		this.vertexShader=vertexShader;			
	}
	
	public void setFragmentShader(JOGLShader fragmentShader)
	{
		this.fragmentShader=fragmentShader;			
	}	
	
	private boolean compile()
	{
		String errors;
		
		
		
		if(this.vertexShader!=null)
			this.vertexShader.compile();
			
		if(this.fragmentShader!=null)
			this.fragmentShader.compile();
			
		if(this.vertexShader!=null)	
			System.out.println("vertexShader id = " + this.vertexShader.getId());
		
		if(this.fragmentShader!=null)
			System.out.println("vertexShader id = " + this.fragmentShader.getId());
		
		
		this.programId = this.gl.glCreateProgramObjectARB();
		
		if(this.vertexShader!=null)
			this.gl.glAttachObjectARB(this.programId, this.vertexShader.getId());
			
		if(this.fragmentShader!=null)	
			this.gl.glAttachObjectARB(this.programId, this.fragmentShader.getId());
			
		this.gl.glLinkProgramARB(this.programId);
		
		if ((errors = getGLError(this.gl)) != null)
			System.out.println("Shader linkage error :\n" + errors);
		
		/*	
			gl.glUseProgramObjectARB(programId);
			
			int texUnit0 = gl.glGetUniformLocationARB(programId, "texUnit0");
	
			gl.glUniform1iARB(texUnit0, 0);	
			
			gl.glUseProgramObjectARB(0);			
		*/
			
		this.compiled=true;	
		
		return true;
	}
	
	public void setEnable(boolean flag)
	{
		if(!this.compiled)
			this.compile();
		if(flag)
		{
			
			this.gl.glUseProgramObjectARB(this.programId);
			return;
		}
		this.gl.glUseProgramObjectARB(0);
		
	}	
	
	private String getGLError(GL gl)
	{
		boolean hasError = false;
		String message = "";
		for (int glErr = gl.glGetError(); glErr != GL.GL_NO_ERROR; glErr = gl.glGetError())
		{
			message += (hasError ? "\n" : "") + glu.gluErrorString(glErr);
			hasError = true;
		}
		return hasError ? message : null;
	}
}