module FRP.Yampa.SDL.Event where

import Graphics.UI.SDL hiding (Event, NoEvent)
import qualified Graphics.UI.SDL as SDL
import FRP.Yampa as Y
import Data.Word (Word32)

type Events = [SDL.Event]

isKey k (Keysym ks _ _) | k == ks = True
isKey _ _ = False

-- | This event occurs a specified amount of times per second. Very useful for the redrawing event.
fps :: Int -> SF a (Event ())
fps f = repeatedly (1.0 / (fromIntegral f)) ()

quit :: SF Events (Event ())
quit = edge <<< arr (elem SDL.Quit)

keysDown :: SF Events [Keysym]
keysDown = arr $ map fromKeyDown . filter isKeyDownEvent
    where
        fromKeyDown (SDL.KeyDown k) = k
        isKeyDownEvent (SDL.KeyDown _) = True
        isKeyDownEvent _ = False

keyDown :: SDLKey -> SF Events (Event ())
keyDown k = edge <<< arr (not . null . filter (isKey k)) <<< keysDown

mousePosition :: SF Events (Int, Int)
mousePosition = hold (0,0) <<< arr f
    where
        f ev | null e = NoEvent
             | otherwise = Event $ c $ last e
             where
                e = filter f' ev
                f' (MouseMotion _ _ _ _) = True
                f' _ = False
                c (MouseMotion x y _ _) = (fromIntegral x, fromIntegral y)
