{-|
Module      : EventLoop.Input.Mouse
Description : Library of all the possible 'Mouse' events in the example implementation.
Copyright   : (c) Sebastiaan la Fleur, 2014
License     : BSD3
Maintainer  : sebastiaan.la.fleur@gmail.com
Stability   : experimental
Portability : All

This module expresses how the 'Mouse' IO device is modelled in the example implementation. 
-}
module EventLoop.Input.Mouse(
    Mouse(..),
    MouseButton(..)
) where

import EventLoop.Json
import EventLoop.Config
import EventLoop.CommonTypes

{-|
 Datatype to express the different 'Mouse' events. 
 The 'EventLoop.CommonTypes.Pos' expresses where on the screen the event happened.
 The 'Element' expresses on which top element on screen the event happened. The 'Element' value is the name of the 'EventLoop.Output.Graphical.GObject'.
-}
data Mouse = MouseClick MouseButton Pos Element -- ^ Expresses a complete 'MouseClick' consisting of a 'MouseUp' and a 'MouseDown'.
           | MouseUp MouseButton Pos Element    -- ^ Expresses when a 'MouseButton' moves upward.
           | MouseDown MouseButton Pos Element  -- ^ Expresses when a 'MouseButton' is pushed down.
           deriving Show

-- | The 'MouseButton' on the mouse.           
data MouseButton = MLeft | MRight | MMiddle
                    deriving Show

-- | How to parse a 'Mouse'event from a JSON formatted 'String'. 
instance FromJSON Mouse where
    fromJsonMessage (JSONObject ms) | mouseType == mouseclickS = MouseClick button pos element
                                    | mouseType == mouseupS    = MouseUp button pos element
                                    | mouseType == mousedownS  = MouseDown button pos element
                                    where
                                        JSONString mouseType = retrieveError mousetypeS ms
                                        JSONFloat x = retrieveError xS ms
                                        JSONFloat y = retrieveError yS ms
                                        pos = (x, y)
                                        JSONString element = retrieveError elementS ms
                                        jsonButton = retrieveError buttonS ms
                                        button = fromJsonMessage jsonButton

-- | How to parse a 'MouseButton' from a JSON formatted 'String'.                                         
instance FromJSON MouseButton where
    fromJsonMessage (JSONString but) | leftS   == but = MLeft
                                     | middleS == but = MMiddle
                                     | rightS  == but = MRight
                                     | otherwise = error ("Could not create a mouse button from value: " ++ but)