package sfs.cluster.lobby.handlers.client;

import it.gotoandplay.smartfoxserver.SmartFoxServer;
import it.gotoandplay.smartfoxserver.data.User;
import it.gotoandplay.smartfoxserver.extensions.AbstractExtension;

import java.util.LinkedList;
import java.util.logging.Logger;

import org.json.JSONObject;

import sfs.cluster.lobby.ClusterLobbyExtension;
import sfs.cluster.lobby.DataStore;
import sfs.cluster.lobby.data.ClusterEvent;

/**
 * Handles the creation of a new game room
 */
public class CreateGameHandler implements IClientRequestHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	
	public CreateGameHandler(AbstractExtension parentExtension)
    {
	    this.parentExtension = (ClusterLobbyExtension) parentExtension;
	    log = SmartFoxServer.log;
	}
	
	// Handle the event
	public void handleRequest(Object req, User sender, int roomId) throws Exception
	{
	    JSONObject jso = (JSONObject) req;
	    String gameName = jso.getString("gameName");
	    String gameType = jso.getString("gameType");
	    
	    // See if game type exists
	    String gameServerNodeId = DataStore.instance().locateGameServerNode(gameType);
	    
	    // Let's create the game
	    if (gameServerNodeId != null)
	    {
	    	ClusterEvent event = new ClusterEvent(ClusterEvent.ON_CREATE_GAME);
	    	event.getParams().put("owner", sender.getName());
	    	event.getParams().put("gameName", gameName);
	    	event.getParams().put("gameType", gameType);
	    	event.getParams().put("expiry", "30");
	    	
	    	// Fire cluster event
	    	System.out.println("Dispatching room created event to ->" + gameServerNodeId);
	    	DataStore.instance().dispatchClusterEvent(event, gameServerNodeId);
	    	
	    	// Send a response to the client
	    	JSONObject response = new JSONObject();
	    	response.put("_cmd", "createGame");
	    	response.put("gameServer", gameServerNodeId);
	    	response.put("gameRoomName", gameName);
	    	response.put("gameType", gameType);
	    	
	    	LinkedList<Object> recipients = new LinkedList<Object>();
		    recipients.add(sender.getChannel());
		    
		    parentExtension.sendResponse(response, -1, null, recipients);
	    }
	    
	    // game type not found
	    else
	    {
	    	log.warning("Room Create FAILED. Requested game type doesn't exist: " + gameType);
	    }
	}
}
