{-|
Module      : EventLoop.Output.SystemMessage
Description : Library of all the possible output 'SystemMessage' 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 outgoing 'SystemMessage's are modelled in the example implementation. 
-}
module EventLoop.Output.SystemMessage(SystemMessageOut(..), TimeData(..)) where

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

{-|
 The different possible 'SystemMessageOut's.
-}
data SystemMessageOut = CanvasSetup Dimension -- ^ Answer to the 'EventLoop.Input.SystemMessage.Setup' containing the dimensions of the canvas that will be used.
                      | Timer TimeData            -- ^ Request to create a timer at the clientside that will generate a 'EventLoop.Input.SystemMessage.Time' message each \'tick\'.
                      | Close                 -- ^ A request for the client to completely close the connection to the server.
                      
data TimeData = On Int -- ^ Tells that the timer should be on with the time in ms
              | Off    -- ^ Tells that the timer should be off

{-|
 Instance to express how to parse a 'SystemMessageIn' to a JSON formatted 'String'.
-}                      
instance JSONAble SystemMessageOut where
    toJsonMessage (CanvasSetup dim) = JSONObject [(JSONMember sysmessageanswerS (JSONString canvassetupS)), (JSONMember dimensionS (dimensionToJsonMessage dim))]
    toJsonMessage (Timer timedata)  = JSONObject [(JSONMember sysmessageanswerS (JSONString timerS)), (JSONMember timedataS (toJsonMessage timedata))]
    toJsonMessage (Close)           = JSONObject [(JSONMember sysmessageanswerS (JSONString closeS))]
    
-- | Private
dimensionToJsonMessage :: Dimension -> JSONMessage
dimensionToJsonMessage (w, h) = JSONObject [(JSONMember hS (JSONFloat h)), (JSONMember wS (JSONFloat w))]

{-|
 Instance to express how to parse a 'TimeData' to a JSON formatted 'String'.
-}    
instance JSONAble TimeData where
    toJsonMessage Off    = JSONObject [(JSONMember useS (JSONBool False))]
    toJsonMessage (On i) = JSONObject [(JSONMember useS (JSONBool True)), (JSONMember iS (JSONFloat $ fromIntegral i))]