module Irg.Lab1.Callbacks (
  reshapeCallback,
  keyboardCallback,
  mouseCallback
) where

import qualified Graphics.GL.Compatibility33 as GL
import qualified Graphics.UI.GLUT as GLUT
import Irg.Lab1.GL.Utility
import Irg.Lab1.Bresenham

reshapeCallback :: GLUT.Size -> IO ()
reshapeCallback (GLUT.Size newWidth newHeight) = do
  GL.glViewport 0 0 newWidth newHeight
  GL.glMatrixMode GL.GL_PROJECTION
  GL.glLoadIdentity
  GLUT.ortho2D 0 (fromIntegral newWidth) (fromIntegral newHeight) 0
  GL.glMatrixMode GL.GL_MODELVIEW
  GL.glLoadIdentity

  GL.glClearColor 1 1 1 0
  GL.glClear GL.GL_COLOR_BUFFER_BIT
  let minFat = 1.0
  GL.glLineWidth minFat
  GL.glPointSize minFat
  GL.glColor3f 0 0 0

keyboardCallback :: Char -> GLUT.Position -> IO ()
keyboardCallback key (GLUT.Position x y) = do
  print key >> print x >> print y

  case key of
    '\r' -> GLUT.leaveMainLoop
    'r'  -> GL.glColor3f 1 0 0
    'g'  -> GL.glColor3f 0 1 0
    'b'  -> GL.glColor3f 0 0 1
    'k'  -> GL.glColor3f 0 0 0
    _    -> return ()

  (w, h) <- getWindowSize
  GL.glRecti w h (w-20) (h-20)
  GL.glFlush


mouseCallback :: GLUT.MouseButton -> GLUT.KeyState -> GLUT.Position -> IO ()
mouseCallback GLUT.LeftButton GLUT.Down (GLUT.Position x y) = do
  (w, h) <- getWindowSize
  GL.glBegin GL.GL_LINES
  GL.glVertex2f (fromIntegral x+30) (fromIntegral y)
  GL.glVertex2f (fromIntegral $ w `div` 2 + 30) (fromIntegral $ h `div` 2)
  GL.glEnd
  --GL.glFlush
  GL.glBegin GL.GL_POINTS
  mapM_ (uncurry GL.glVertex2i) $ bresenham (w `div` 2, h `div` 2) (fromIntegral x, fromIntegral y)
  GL.glEnd

mouseCallback GLUT.RightButton GLUT.Down _ = GLUT.get GLUT.windowSize >>= reshapeCallback
mouseCallback _ _ _ = return ()
