package sfs.cluster.lobby.handlers.cluster;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.Room;
import it.gotoandplay.smartfoxserver.data.Zone;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

import java.util.logging.Logger;

import sfs.cluster.lobby.ClusterGameServerExtension;
import sfs.cluster.lobby.data.ClusterEvent;
import sfs.cluster.lobby.data.RoomReservation;

/**
 * This event is received when a user wants to join a room on game node.
 * A Reservation is created to allow the user connec to the new node and finally join the desired room.
 */
public class OnJoinGame implements IClusterEvtHandler
{
	ClusterGameServerExtension parentExtension;
	Logger log;
	Zone zone;
	
	public OnJoinGame(AbstractExtension parentExtension)
    {
		this.parentExtension = (ClusterGameServerExtension) parentExtension;	
	    this.zone = SmartFoxServer.getInstance().getZone(parentExtension.getOwnerZone());
	    log = SmartFoxServer.log;
    }
	
	// Handle event
	public void handleClusterEvent(ClusterEvent event) throws Exception
	{
		String who = (String) event.getParams().get("who");
		int gameId = Integer.parseInt((String) event.getParams().get("gameName"));
		
		int expiry = Integer.parseInt((String) event.getParams().get("expiry"));
		
		Room gameRoom = zone.getRoom(gameId);
		
		if (gameRoom != null)
		{
			RoomReservation reservation = new RoomReservation(who, gameRoom.getId(), expiry);
			parentExtension.addReservation(reservation);
			log.info("Join Reservation created: " + reservation);
		}
		else
		{
			log.warning("Room join request failure, roomId -> " + gameId + " doesn't exist on this server: " + parentExtension.getNodeId());
		}
	}
}
