package sfs.cluster.lobby.handlers.internal;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.Room;
import it.gotoandplay.smartfoxserver.events.InternalEventObject;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

import java.util.List;
import java.util.logging.Logger;

import sfs.cluster.lobby.ClusterGameServerExtension;
import sfs.cluster.lobby.DataStore;
import sfs.cluster.lobby.data.ClusterEvent;
import sfs.cluster.lobby.data.ClusterRoom;

/**
 * Handle joining a game room
 */
public class GameJoinHandler implements InternalHandler
{
	ClusterGameServerExtension parentExtension;
	Logger log;
	
	public GameJoinHandler(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterGameServerExtension) parentExtension;
	    log = SmartFoxServer.log;
    }
	
	// Handle the event
	public void handleInternalEvent(InternalEventObject ieo) throws Exception
	{
		Room localGameRoom = (Room) ieo.getObject("room");
		
		if (localGameRoom != null)
		{
			// get the room from the datastore
			ClusterRoom gameRoom = DataStore.instance().clusterRoomsByName.get(localGameRoom.getName());
		    
		    if (gameRoom != null)
		    {
		    	// increment the user count
		    	gameRoom.getPlayerCount().incrementAndGet();
		    	
		    	// fire a global game-room update
		    	ClusterEvent event = new ClusterEvent(ClusterEvent.ON_GAME_UPDATE);
		    	event.getParams().put("gameName", localGameRoom.getName());
		    	event.getParams().put("gameType", parentExtension.getGameType());
		    	event.getParams().put("debug", "join");
		    	
		    	// Broadcast cluster event to all lobby nodes in the cluster
		    	List<String> nodeList = DataStore.instance().getLobbyNodes();
			    DataStore.instance().broadcastClusterEvent(event, nodeList);
			    
		    }
		    else
		    {
		    	log.warning("Room not found: " + localGameRoom + " while handling user exit/lost/logout.");
		    }
		}
		else
		{
			log.warning("User joined a non-existent Room!");
		}
	}
}
