package world;

import java.util.ArrayList;

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

import com.sun.opengl.util.GLUT;

import eng.Data;
import eng.Input;

public class GameWorld {
	
	protected GLU glu;
	protected GLUT glut;
	
	protected Camera camera;
	
	protected ArrayList<GameObject> objects;
	
	protected Data data;
	
	public GameWorld(GL gl) {
		
		glu = new GLU();
		glut = new GLUT();
		
		objects = new ArrayList<GameObject>();
		
		addGameObjects(gl);
	}
	
	public void update(Camera camera, Input input, Data data) {
		
		this.camera = camera;
		this.data = data;
		
		for(int i = 0; i < objects.size(); i++) {
			
			objects.get(i).setData(data);
			objects.get(i).setCamera(camera);
			objects.get(i).setInput(input);
			
			objects.get(i).update();
			
			for(int j = 0; j < objects.size(); j++)
				objects.get(i).interact(objects.get(j));
			
			objects.get(i).inspectScene(objects);
			
			this.camera = objects.get(i).getCamera();
			data = objects.get(i).getData();
		}
		
		for(int i = 0; i < objects.size(); i++) {
			
			ArrayList<GameObject> spawn = objects.get(i).getSpawn();
			
			for(int j = 0; j < spawn.size(); j++)
				objects.add(spawn.get(j));
		}
		
		for(int i = 0; i < objects.size(); i++)
			
			if(!objects.get(i).doesExist()) {
				
				objects.remove(i);
				i--;
			}
	}
	
	public Camera getCamera() {
		return camera;
	}
	
	public Data getData() {
		return data;
	}
	
	public String getTriggeredGameState() {
		
		for(int i = 0; i < objects.size(); i++)
			
			if(objects.get(i).getTriggeredGameState() != null) {
				
				String triggeredGameState = objects.get(i).getTriggeredGameState();
				objects.get(i).setTriggeredGameState(null);
				
				return triggeredGameState;
			}
		
		return null;
	}
	
	public boolean isScenePaused() {
		
		for(int i = 0; i < objects.size(); i++)
			
			if(objects.get(i).isScenePaused()) {
				
				for(int j = 0; j < objects.size(); j++)
					objects.get(j).onPause();
				
				return true;
			}
		
		return false;
	}
	
	public boolean isSceneEnded() {
		
		for(int i = 0; i < objects.size(); i++)
			
			if(objects.get(i).isSceneEnded()) {
				
				for(int j = 0; j < objects.size(); j++)
					objects.get(j).onEnd();
				
				return true;
			}
		
		return false;
	}
	
	public void render(GL gl) {
		
		for(int i = 0; i < objects.size(); i++) {
			objects.get(i).setGLUtilities(glu, glut);
			objects.get(i).render(gl);
		}
	}
	
	protected void addGameObjects(GL gl) {
		
	}
}