import qualified Graphics.UI.SDL as SDL
import qualified System.Random as Rand
import Control.Monad
import Data.Word
    
type RGB = (Word8, Word8, Word8)
    
scrW :: Int
scrW = 600
       
scrH :: Int
scrH = 600

randRGB :: IO RGB
randRGB = do
  r <- Rand.randomIO :: IO Word8
  g <- Rand.randomIO :: IO Word8
  b <- Rand.randomIO :: IO Word8
  return (r, g, b)

         
randRect :: IO SDL.Rect
randRect = do
  x <- Rand.randomRIO (0, 600) :: IO Int
  y <- Rand.randomRIO (0, 600) :: IO Int
  -- w <- Rand.randomRIO (0, 600 - x) :: IO Int
  -- h <- Rand.randomRIO (0, 600 - y) :: IO Int
  return $ SDL.Rect x y 20 20
  

randDraw :: SDL.Surface -> IO Bool
randDraw screen = do
  (r, g, b) <- randRGB
  let format = SDL.surfaceGetPixelFormat screen
  color <- SDL.mapRGB format r g b
  rect <- randRect
  SDL.fillRect screen (Just rect) color


clearSurface :: SDL.Surface -> IO ()
clearSurface screen = do
  (r, g, b) <- randRGB
  let format = SDL.surfaceGetPixelFormat screen
  color <- SDL.mapRGB format r g b
  SDL.fillRect screen Nothing color
  SDL.flip screen


eventLoop :: IO ()
eventLoop = SDL.waitEvent >>= handleEvent
    where
      handleEvent SDL.Quit = return ()
      handleEvent (SDL.KeyDown _) = do
        watdo <- Rand.randomIO :: IO Float
        if watdo > 0.8
        then SDL.getVideoSurface >>= clearSurface
        else do
          replicateM_ 50 $ SDL.getVideoSurface >>= randDraw
          SDL.getVideoSurface >>= SDL.flip
        eventLoop
      handleEvent _ = eventLoop


main :: IO ()
main = SDL.withInit [SDL.InitEverything] $ do
         vs <- SDL.setVideoMode scrW scrH 32 []
         SDL.setCaption "Moneygrab" "Monadgrab"
         clearSurface vs
         eventLoop
