package com.android.draw3d;

import java.io.IOException;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import org.opencv.core.Point3;

import android.content.Context;
import android.opengl.GLES10;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.util.Log;

public class ObjModelRenderer implements GLSurfaceView.Renderer {
	private Context mContext;
	private ObjModel mModel;

	private int zoom = 0;
	private float panX = 0.0f;
	private float panY = 0.0f;
	private float distance = 6;
	private float elevation = 45;
	private float rotation = 45;

	private Point3 mOrigin;
	private Point3 mRotate;
	private Point3 mCamera;

	public int NONE = -1;
	public final static int X_AXIS = 0;
	public final static int Y_AXIS = 1;
	public final static int Z_AXIS = 2;

	float mRotationFinal = -1f;
	float mRotationDelta = 0f;
	int mRotationAxis = -1;

	public ObjModelRenderer(Context context) {
		mContext = context;
		mModel = new ObjModel(mContext);

		try {
			mModel.ObjLoader();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black
		gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest
		gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal
		gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view
		gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color
		gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		if (height == 0)
			height = 1; // To prevent divide by zero
		float aspect = (float) width / height;

		// Set the viewport (display area) to cover the entire window
		gl.glViewport(0, 0, width, height);

		// Setup perspective projection, with aspect ratio matches viewport
		gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix
		gl.glLoadIdentity(); // Reset projection matrix
		// Use perspective projection
		GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f);

		gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
		gl.glLoadIdentity(); // Reset
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		// ----- Render the Color Cube -----
		gl.glLoadIdentity(); // Reset the model-view matrix
		gl.glTranslatef(1.5f, 0.0f, -6.0f); // Translate right and into the
											// screen
		gl.glScalef(0.8f, 0.8f, 0.8f); // Scale down (NEW)
		gl.glRotatef(90, 1.0f, 1.0f, 1.0f); // rotate about the axis
													// (1,1,1) (NEW)
		mModel.draw(gl);
		//angleModel += speedCube; // (NEW)
	}
}
