package sfs3.extensions.examples.spacewar2.handlers.requests;

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

import sfs3.extensions.examples.spacewar2.SW2RoomExtension;
import sfs3.extensions.examples.spacewar2.util.Constants;

@Instantiation
@MultiHandler
public class ControlRequestHandler extends BaseClientRequestHandler
{
	@Override
	public void handleClientRequest(User sender, ISFSObject params, TransportType transportType)
	{
		// Get the request id
        String requestId = params.getString(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).getString("weapon" + weaponNum);
		
		// Add weapon shot to game
		roomExt.getGame().fireWeaponShot(user.getId(), roomExt.getWeaponsCfg().getSFSObject(weaponModel));
	}
}
