-- $LastChangedDate: 2008-12-26 21:33:34 -0500 (Fri, 26 Dec 2008) $
-- Joystick handler.
-- C++ handles joystick axis events.
-- Lua handles joystick button events.
-- See module.txt for documentation and pitfalls.

--------------
-- Joystick --
--------------
Joystick = {
	BUTTON_FIRE_GUN            = 0,
	BUTTON_FIRE_MISSILE        = 2,
	BUTTON_BRAKES              = 1,
	BUTTON_SELECT_TARGET       = 3,
	BUTTON_WING_SWEEP_FORWARD  = 4,
	BUTTON_WING_SWEEP_BACKWARD = 5,
}

-- Joystick handler (button).
-- sim.Joystick:DequeueButton() returns nil or a table:
-- { buttonNum=int, buttonVal=bool }
function Joystick:Handler()
	-- If player has crashed, ignore joystick input.
	-- (Well, Lua can only discard button events.)
	if ( PlayerActor:IfDestroyed() ) then
		return
	end

	local joyButtonEvent = sim.Joystick:DequeueButton()
	if ( joyButtonEvent ) then
		local pressed = joyButtonEvent.buttonVal

		-- Button pressed or released.
		if ( joyButtonEvent.buttonNum == self.BUTTON_BRAKES ) then
			PlayerActor.aircraft:EnableBrakes( joyButtonEvent.buttonVal )
		end

		-- Button pressed.
		if ( pressed ) then
			if ( joyButtonEvent.buttonNum == self.BUTTON_FIRE_GUN ) then
				PlayerActor:FireGun()
			elseif ( joyButtonEvent.buttonNum == self.BUTTON_FIRE_MISSILE ) then
				PlayerActor:FireMissile()
			elseif ( joyButtonEvent.buttonNum == self.BUTTON_SELECT_TARGET ) then
				PlayerActor:CycleTargets()
			elseif ( joyButtonEvent.buttonNum == self.BUTTON_WING_SWEEP_FORWARD  ) then
				Joystick.repeatIncWingSweep = 1
			elseif ( joyButtonEvent.buttonNum == self.BUTTON_WING_SWEEP_BACKWARD  ) then
				Joystick.repeatIncWingSweep = -1
			end
		else -- button released
			Joystick.repeatIncWingSweep = nil
		end
	end

	-- Repeat some joystick buttons until released.
	if ( Joystick.repeatIncWingSweep ) then
		PlayerActor:IncWingSweep( Joystick.repeatIncWingSweep, "joy" )
	end
end
