package com.programmez.opengl.exercice1;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import com.programmez.opengl.exercice1.R;

import android.content.Context;
import android.opengl.GLSurfaceView;

import static android.opengl.GLES10.*;

class CubeRenderer implements GLSurfaceView.Renderer {
	private final Context context;

	private final GLCube cube = new GLCube();
	private float mAngleX;
	private float mAngleY;

	public float getmAngleX() {
		return mAngleX;
	}

	public void setmAngleX(float mAngleX) {
		this.mAngleX = mAngleX;
	}

	public float getmAngleY() {
		return mAngleY;
	}

	public void setmAngleY(float mAngleY) {
		this.mAngleY = mAngleY;
	}

	CubeRenderer(Context context) {
		this.context = context;
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {

		glDisable(GL10.GL_DITHER);
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);

		float ambiantLight[] = new float[] { 0.2f, 0.2f, 0.2f, 1 };
		float diffuseLight[] = new float[] { 1, 1, 1, 1 };
		float[] lightPos = new float[] { 1, 1, 1, 1 };
		glEnable(GL10.GL_LIGHTING);
		glEnable(GL10.GL_LIGHT0);
		glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, ambiantLight, 0);
		glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, diffuseLight, 0);
		glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPos, 0);

		float matAmbient[] = new float[] { 1, 1, 1, 1 };
		float matDiffuse[] = new float[] { 1, 1, 1, 1 };
		glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, matAmbient, 0);
		glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, matDiffuse, 0);

		glEnable(GL10.GL_DEPTH_TEST);
		glDepthFunc(GL10.GL_LEQUAL);
		glEnableClientState(GL10.GL_VERTEX_ARRAY);
		glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		glEnable(GL10.GL_TEXTURE_2D);

		GLCube.loadTexture(gl, context, R.drawable.texture_cube);
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		glViewport(0, 0, width, height);
		glMatrixMode(GL10.GL_PROJECTION);
		glLoadIdentity();
		float ratio = (float) width / height;
		glFrustumf(-ratio, ratio, -1, 1, 1, 10);
	}

	public void onDrawFrame(GL10 gl) {
		glDisable(GL10.GL_DITHER);
		glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		
		glMatrixMode(GL10.GL_MODELVIEW);
		glLoadIdentity();
		glTranslatef(0, 0, -2.0f);

		glRotatef( (mAngleX), 1, 0, 0);
		glRotatef( (mAngleY), 0, 1, 0);
		cube.draw(gl);
	}
}
