package slimpleslickgame;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import util.EventProtocol;
import client.ByteMonitor;
import client.GameStatsEvents;

public class Game extends BasicGameState {
	public static final int ID = 2;

	private GameContainer gc;
	private ByteMonitor bm;
	private List<Player> players;
	private GameStatsEvents gse;

	public void addGSM(GameStatsEvents gse, ByteMonitor byteMonitor) {
		this.bm = byteMonitor;
		this.gse = gse;
	}

	@Override
	public void init(GameContainer gc, StateBasedGame arg1)
			throws SlickException {
		// TODO: Setup game stuff
		this.gc = gc;
		players = Collections.synchronizedList(new ArrayList<Player>());
	}

	@Override
	public void render(GameContainer gc, StateBasedGame arg1, Graphics g)
			throws SlickException {
		// TODO:render all stuff here

		for(Player p : players){
			p.render(g);
		}
	}

	@Override
	public void update(GameContainer gc, StateBasedGame arg1, int delta)
			throws SlickException {
//		Player player = null;
//		if(playerMonitor != null&&(player = playerMonitor.getPlayer()) != null){
//			players.add(player);
//		}
		for(Player p : players){
			p.update(delta);
		}
	}

	@Override
	public int getID() {
		return ID;
	}

	public void addPlayer(byte playerId) {
		OpponentPlayer op = new OpponentPlayer(this.gse, playerId);
		op.init();
		synchronized(players){
			players.add(op);
		}
	}
	
	public void addLocalPlayer(byte playerId){
		LocalPlayer player = new LocalPlayer(gc, bm, playerId);
		player.init();
		synchronized(players){
			players.add(player);
		}
		byte[] msg = {EventProtocol.OPPONENT_PLAYER_INIT};
		bm.putArrayToServer(msg, playerId);
	}
	/**
	 * Closes the connection held by the bytemonitorn.
	 */
	public void onClose(){
		this.bm.closeConnection();
	}
}

@@ -1056,16 +1056,43 @@
 f here%0A%0A
+%09%09synchronized (players)%7B%0A%09
 %09%09for(Pl
@@ -1113,16 +1113,17 @@
 rs)%7B%0A%09%09%09
+%09
 p.render
@@ -1127,16 +1127,21 @@
 der(g);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%0A
@@ -1252,143 +1252,36 @@
 n %7B%0A
-//%09%09Player player = null;%0A//%09%09if(playerMonitor != null&&(player = playerMonitor.getPlayer()) != null)%7B%0A//%09%09%09players.add(player);%0A//%09%09%7D%0A
+%09%09synchronized (players) %7B%0A%09
 %09%09fo
@@ -1306,16 +1306,17 @@
 rs)%7B%0A%09%09%09
+%09
 p.update
@@ -1324,16 +1324,21 @@
 delta);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%0A

synchronize list read