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;

/**
 * Handle the request of a list of games in a certain game node
 */
public class GetGameList implements IClientRequestHandler
{
	ClusterLobbyExtension parentExtension;
	Logger log;
	
	public GetGameList(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 gameType = jso.getString("gameType");
	    
	    if (gameType == null || "".equals(gameType))
	    	return;
	    
	    // set the type of game that the user is watching
	    sender.properties.put("gameType", gameType);
	    
	    net.sf.json.JSONObject response = new net.sf.json.JSONObject();
	    response.put("_cmd", "gameList");
	    response.put("serverInfo", DataStore.instance().locateGameServerNode(gameType));
	    response.put("type", gameType);
	    response.put("list", DataStore.instance().getGameList(gameType));
	    
	    LinkedList recipients = new LinkedList();
	    recipients.add(sender.getChannel());
	    
	    // send list back
	    parentExtension.sendResponse(response, -1, null, recipients);
	    
	}
}
