package com.framsticks.net.client3D;

import java.io.File;
import java.io.IOException;

import javax.media.opengl.GL;

import pl.vorg.mowa.core.graphics.GeometryGroup;

import com.framsticks.net.client3D.graphics.loaders.OBJLoader;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;

/**
 * Podstawowy styl wyswietlania framstickow. Ma najmniejsze wymagania sprzetowe. Powinien dzsialac na wszystkim co wspiera OpenGL'a
 * 
 * @author vorg
 */
public class BasicStyle implements Style {
	private boolean initialized;
	private Texture partTex;
    private Texture jointTex;
    private GeometryGroup partGeo;
    private GeometryGroup jointGeo;
    
	public void init(GL gl) {
		try {
			partGeo = OBJLoader.load("res/obj/part.obj");
			partTex = TextureIO.newTexture(new File("res/img/green2.png"), false);
			partTex.bind();
			partTex.setTexParameteri(GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
			partTex.setTexParameteri(GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
			
			jointGeo = OBJLoader.load("res/obj/stick5red.obj");
			jointTex = TextureIO.newTexture(new File("res/img/green4.png"), false);
			jointTex.bind();
			jointTex.setTexParameteri(GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
			jointTex.setTexParameteri(GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
		}
		catch(IOException e) {
			Log.getInstance().log("err", e.getClass().getName() + " : " + e.getMessage());
			initialized = false; 
			return;
		}
		initialized = true; 
	}
	
	public boolean isInitialized() {
		return initialized;
	}

	public void render(GL gl, Creature[] creatures, Creature.ModelType modelType) {
		
//		gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[] { 5, -5, 5}, 0);
		gl.glEnable(GL.GL_LIGHT0);
		gl.glEnable(GL.GL_LIGHTING);
		
		//parts
		
		partTex.enable();
		partTex.bind();		
		for(Creature creature : creatures) {
			float[][] parts = creature.getParts(modelType);
			for(int i=0; i<creature.getParts(modelType).length; i++) {
				gl.glPushMatrix();
				gl.glTranslatef(parts[i][0], parts[i][1], parts[i][2]);
				gl.glScalef(0.7f, 0.7f, 0.7f);
				partGeo.display(gl);
				gl.glPopMatrix();
			}	
		}
		partTex.disable();
		
		//joints
		
		jointTex.enable();
		jointTex.bind();
		for(Creature creature : creatures) {
			int[][] joints = creature.getJoints();
			for(int i=0; i<joints.length; i++) {
				gl.glPushMatrix();
				float[] t = creature.jointTranslation(i, modelType);
				float[] r = creature.jointRotation(i, modelType);
				float l = creature.jointLength(i, modelType);
				gl.glTranslatef(t[0], t[1], t[2]);
				gl.glRotatef(r[0], r[1], r[2], r[3]);
				gl.glScalef(1.0f , 1.0f, l);
				jointGeo.display(gl);
				gl.glPopMatrix();
			}		
		}
		jointTex.disable();

		gl.glDisable(GL.GL_LIGHT0);
		gl.glDisable(GL.GL_LIGHTING);
	}

}
