package sfs.cluster.lobby.handlers.internal;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.Room;
import it.gotoandplay.smartfoxserver.data.User;
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;

/**
 * Handles the user log-out from a game node
 */
public class GameLogoutHandler implements InternalHandler
{
	ClusterGameServerExtension parentExtension;
	Logger log;
	
	public GameLogoutHandler(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterGameServerExtension) parentExtension;
	    log = SmartFoxServer.log;
    }
	
	// Handle the event
	public void handleInternalEvent(InternalEventObject ieo) throws Exception
	{
	    int roomIds[] = (int[]) ieo.getObject("roomIds");
	    Room localGameRoom = null;
	    
	    User user = (User) ieo.getObject("user");
	    log.info("User left the server -> " + user.getName());
	    
	    // handle logout / user-lost
	    if (roomIds != null && roomIds.length > 0)
	    {
	    	localGameRoom = parentExtension.getCurrentZone().getRoom(roomIds[0]);
	    }
	    
	    // handle user-exit
	    else
	    {
	    	localGameRoom = (Room) ieo.getObject("room");
	    }
	    
	    // Locate the room
	    ClusterRoom gameRoom = DataStore.instance().clusterRoomsByName.get(localGameRoom.getName());
	    
	    if (gameRoom != null)
	    {
	    	// decrement user count
	    	gameRoom.getPlayerCount().decrementAndGet();
	    	
	    	// fire cluster 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", "userExit");
	    	
	    	// 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.");
	    }
	}
}
