package sfs2x.extensions.games.spacewar2.game.handlers.requests;

import com.smartfoxserver.v2.annotations.Instantiation;
import com.smartfoxserver.v2.annotations.MultiHandler;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.smartfoxserver.v2.extensions.SFSExtension;

import sfs2x.extensions.games.spacewar2.game.SW2RoomExtension;
import sfs2x.extensions.games.spacewar2.shared.util.Constants;

@Instantiation
@MultiHandler
public class ControlRequestHandler extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User sender, ISFSObject params)
	{
		// Get the request id
        String requestId = params.getUtfString(SFSExtension.MULTIHANDLER_REQUEST_ID);
        
        SW2RoomExtension roomExt = (SW2RoomExtension) this.getParentExtension();
        
        if (roomExt.isGameRunning())
        {
	        // SHIP ROTATION CONTROL
	        if (requestId.equals(Constants.REQ_CONTROL_ROTATE))
	        	roomExt.getGame().rotateStarship(sender.getId(), params.getInt("dir"));
	        
	        // SHIP THRUST CONTROL
	        else if (requestId.equals(Constants.REQ_CONTROL_THRUST))
	        	roomExt.getGame().thrustStarship(sender.getId(), params.getBool("go"));
	        
	        // SHIP WEAPON FIRE
	        else if (requestId.equals(Constants.REQ_CONTROL_FIRE))
	        	onWeaponFired(roomExt, sender, params.getInt("wnum"));
        }
	}
	
	/**
	 * Retrieves the fired weapon settings and creates the weapon shot in the core game engine.
	 */
	private void onWeaponFired(SW2RoomExtension roomExt, User user, int weaponNum)
	{
		// Get starship model selected by user and saved in User Variables
		String shipModel = user.getVariable(Constants.USERVAR_SHIP_MODEL).getStringValue();
		
		// Get weapon model assigned to ship
		String weaponModel = roomExt.getStarshipsCfg().getSFSObject(shipModel).getUtfString("weapon" + weaponNum);
		
		// Add weapon shot to game
		roomExt.getGame().fireWeaponShot(user.getId(), roomExt.getWeaponsCfg().getSFSObject(weaponModel));
	}
}
