/*******************************************************************************************
 * 
 * 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 java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import sfs2x.extensions.games.spacerace.SpaceRaceGameExtension;
import sfs2x.extensions.games.spacerace.SpaceRaceZoneExtension;

import com.smartfoxserver.v2.SmartFoxServer;
import com.smartfoxserver.v2.annotations.Instantiation;
import com.smartfoxserver.v2.annotations.Instantiation.InstantiationMode;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.variables.RoomVariable;
import com.smartfoxserver.v2.entities.variables.SFSRoomVariable;
import com.smartfoxserver.v2.entities.variables.VariableType;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;


/**
 * SFS2X Space Race demo - SpaceCraftUpdate Handler
 * Called when Racers send their updated position within a race
 *  
 * @author A51 Integrated
 *
 */
@Instantiation(InstantiationMode.SINGLE_INSTANCE)
public class SpacecraftUpdate extends BaseClientRequestHandler
{
	SpaceRaceGameExtension gameExt; 
	String TIMESTAMP_RECEIVED	= "R";
		
	@Override
	public void handleClientRequest(User user, ISFSObject params)
	{
		
		// Get a reference to the parent extension
		gameExt = (SpaceRaceGameExtension) getParentExtension();
		// Store the time the game is created
		if (gameExt.startTime == 0)
		{
			Date now = new Date();
			gameExt.startTime = now.getTime();
		}
		
		// Add the offset from race start that this message was received and add to the incoming object
		Date now = new Date();
		long currentTime = now.getTime();
		long received_time = currentTime - gameExt.startTime;
		params.putLong(TIMESTAMP_RECEIVED, received_time);
		
		// Add the user's incoming update object to the object sent to all racers 
		gameExt.obj.putSFSObject(user.getName(), params);
		
		// Extract the checkpoint the racer has just crossed from the incoming array
		Object[] param = params.getShortArray("s").toArray();
		Short checkPoint = 0; 
		for(int i = 0; i < param.length; i++)
		{
			checkPoint = (Short) param[8];
		}
		
		// When user has finished the race, update their RoomVariable with their race time so the ranking list is correct
		if (checkPoint.intValue() == 655)
		{
			Room curRoom = user.getLastJoinedRoom();
			ISFSObject obj = new SFSObject();
			List<RoomVariable> varList = curRoom.getVariables();
			
			Iterator<RoomVariable> iterator = varList.iterator();
			while (iterator.hasNext())
			{
				RoomVariable variable = iterator.next();
				if (variable.getType() == VariableType.OBJECT)
				{
					obj = (SFSObject) variable.getSFSObjectValue();
					
					if (obj.containsKey(SpaceRaceZoneExtension.PLAYER_NAME))
					{
						// Update the variable this user is associated with
						if (obj.getUtfString(SpaceRaceZoneExtension.PLAYER_NAME).equalsIgnoreCase(user.getName()))
						{
							// Only update their race time 1 time 
							if (!obj.containsKey("t"))
							{
								SFSObject new_obj = new SFSObject();
								new_obj.putUtfString(SpaceRaceZoneExtension.PLAYER_NAME, user.getName());
								new_obj.putInt("t", (int) (received_time));
								
								RoomVariable var = new SFSRoomVariable(variable.getName(), new_obj);
								List<RoomVariable> listOfVars = new ArrayList<RoomVariable>();
								listOfVars.add(var);
								
								// Update the RoomVariables
								SmartFoxServer.getInstance().getAPIManager().getSFSApi().setRoomVariables(user, curRoom, listOfVars);
							}
						}
					}
				}				
			}
		}
	}
}