/*******************************************************************************************
 * 
 * TITLE: 		SFS2X Space Race
 * VERSION:		1.0
 * RELEASE:		2011-03-15
 * COPYRIGHT:	2011 gotoAndPlay() - http://www.smartfoxserver.com
 * DEVELOPER:	A51 Integrated - http://a51integrated.com
 * 
 * This file is part of SFS2X Space Race.
 * 
 * Contributers: Wayne Helman, Fabricio Medeiros, David Irons,
 * 				 Steve Schoger, Ryan Albrecht, Andy Rohan
 * 
 * SFS2X Space Race is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * included license for more details.
 *
 * You are not allowed to rent, lend, lease, license or distribute SFS2X Space Race or a
 * modified version of SFS2X Space Race to any other person or organization in any way.
 * 
 * For commercial licensing information, please contact gotoAndPlay().
 * 
 *******************************************************************************************/

package sfs2x.extensions.games.spacerace.handlers;

import com.smartfoxserver.v2.annotations.Instantiation;
import com.smartfoxserver.v2.annotations.Instantiation.InstantiationMode;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;


import java.util.Iterator;
import java.util.Collection;

import sfs2x.extensions.games.spacerace.SpaceRaceZoneExtension;

/**
 * SFS2X Space Race demo - ConnectedUsers Handler
 * Called when a user enters the lobby
 *  
 * @author A51 Integrated
 *
 */
@Instantiation(InstantiationMode.SINGLE_INSTANCE)
public class ConnectedUsers extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User user, ISFSObject params)
	{
		// Obtain a reference to the parent Zone handler
		SpaceRaceZoneExtension zoneExt = (SpaceRaceZoneExtension) getParentExtension();
		
		// Obtain a list of all users in the Space Race zone
		Collection<User> userList = zoneExt.getConnectedUsers();
		
		// Create an SFSObject to send back to user
		ISFSObject respObj = new SFSObject();
		
		//Loop through each user and create an SFSobject for each. 
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext())
		{
			User usr = iterator.next();
			ISFSObject usrObj = new SFSObject();
			
			// Add the user's ID and current status in the Zone
			usrObj.putInt(SpaceRaceZoneExtension.PLAYER_ID, usr.getId());
			usrObj.putUtfString(SpaceRaceZoneExtension.PLAYER_STATUS, usr.getVariable(SpaceRaceZoneExtension.PLAYER_STATUS).getStringValue());
			
			// Add each user's SFSobject to one
			respObj.putSFSObject(usr.getName(), usrObj);
		}
		
		// Send SFSObject containing each user's status to the requesting user using UDP
		zoneExt.send(SpaceRaceZoneExtension.USER_LIST, respObj, user, true);
	}
}