package sfs3.extensions.examples.shooter.handlers;

import com.smartfoxserver.bitswarm.data.TransportType;
import com.smartfoxserver.entities.User;
import com.smartfoxserver.entities.data.ISFSObject;
import com.smartfoxserver.extensions.BaseClientRequestHandler;

import sfs3.extensions.examples.shooter.ShooterExtension;
import sfs3.extensions.examples.shooter.simulation.CombatPlayer;
import sfs3.extensions.examples.shooter.simulation.World;
import sfs3.extensions.examples.shooter.utils.RoomHelper;

public class SpawnMeHandler extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User u, ISFSObject data, TransportType txType)
	{
		World world = RoomHelper.getWorld(this);
		int playerPrefab = data.getInt("prefab").intValue();
		int playerColor = data.getInt("color").intValue();
		boolean newPlayer = world.addOrRespawnPlayer(u, playerPrefab, playerColor);
		
		// Send this player data about all the other players
		if (newPlayer)
			sendOtherPlayersInfo(u);

		// Instantiating more items together with spawning player
		world.spawnItems();
	}

	// Send the data for all the other players to the newly joined client
	private void sendOtherPlayersInfo(User targetUser)
	{
		World world = RoomHelper.getWorld(this);
		
		for (CombatPlayer player : world.getPlayers())
		{
			if (player.isDead())
				continue;
		
			if (player.getSfsUser().getId() != targetUser.getId())
			{
				ShooterExtension ext = (ShooterExtension) getParentExtension();
				ext.clientInstantiatePlayer(player, targetUser);
			}
		}
	}
}
