-- $LastChangedDate: 2010-04-16 09:27:50 -0500 (Fri, 16 Apr 2010) $
-- 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_SWING_WINGS_FORWARD  = 4,
    BUTTON_SWING_WINGS_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 joystickButtonEvent = sim.Joystick:DequeueButton()
    if ( joystickButtonEvent ) then
        local pressed = joystickButtonEvent.buttonVal
        local buttonNum = joystickButtonEvent.buttonNum

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

        -- Button pressed.
        if ( pressed ) then
            if ( buttonNum == self.BUTTON_FIRE_GUN ) then
                PlayerActor:FireGun()
            elseif ( buttonNum == self.BUTTON_FIRE_MISSILE ) then
                PlayerActor:FireMissile()
            elseif ( buttonNum == self.BUTTON_SELECT_TARGET ) then
                PlayerActor:CycleTargets()
            elseif ( buttonNum == self.BUTTON_SWING_WINGS_FORWARD  ) then
                Joystick.repeatIncSwingWings = 1
            elseif ( buttonNum == self.BUTTON_SWING_WINGS_BACKWARD  ) then
                Joystick.repeatIncSwingWings = -1
            end
        else -- button released
            Joystick.repeatIncSwingWings = nil
        end
    end

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