{- Functions that affect the world according to what pressed buttons are stored in a Set.
-}
module Dodge.Update.UsingInput
    ( updateUsingInput
    ) where
import Dodge.Data
import Dodge.Creature.Impulse.UseItem
import Geometry

import SDL
import qualified Data.Set as S
import Control.Lens

updateUsingInput :: World -> World
updateUsingInput w = if _carteDisplay w
    then updatePressedButtonsCarte (_mouseButtons w) w
    else updatePressedButtons (_mouseButtons w) w

updatePressedButtons :: S.Set MouseButton -> World -> World
updatePressedButtons pkeys w 
    | lbPressed && rbPressed 
                = useItem (_yourID w) w & lClickHammer .~ HammerDown
    | lbPressed && canLeftClick = useLeftItem (_yourID w) w
    | lbPressed = w
    | mbPressed = w & clickMousePos .~ _mousePos w 
                    & cameraRot     -~ rotation
    | otherwise = w & lClickHammer .~ HammerUp
  where 
    lbPressed = ButtonLeft `S.member` pkeys
    rbPressed = ButtonRight `S.member` pkeys
    mbPressed = ButtonMiddle `S.member` pkeys
    rotation  = angleBetween (_mousePos w) (_clickMousePos w)
    canLeftClick = _lClickHammer w == HammerUp

updatePressedButtonsCarte :: S.Set MouseButton -> World -> World
updatePressedButtonsCarte pkeys w 
    | rbPressed = w & clickMousePos .~ _mousePos w 
                    & carteCenter   %~ (-.- trans)
    | lbPressed = w & clickMousePos .~ _mousePos w 
                    & carteRot      -~ rot
                    & carteZoom     *~ czoom
    | otherwise = w
  where 
    lbPressed = ButtonLeft `S.member` pkeys
    rbPressed = ButtonRight `S.member` pkeys
    --mbPressed = ButtonMiddle `S.member` pkeys
    rot     = angleBetween (_mousePos w) (_clickMousePos w)
    czoom    = magV (_mousePos w) / magV (_clickMousePos w)
    trans   = rotateV (_carteRot w) $ (1 / _carteZoom w) *.* (_mousePos w -.- _clickMousePos w)
