{-|
Module      : EventLoop.Main
Description : High-level starting point for the eventloop. Uses the example implementation.
Copyright   : (c) Sebastiaan la Fleur, 2014
License     : BSD3
Maintainer  : sebastiaan.la.fleur@gmail.com
Stability   : experimental
Portability : All

High-level starting point for the eventloop. Uses the example implementation of 'EventLoop.Input.InputEvent' and 'EventLoop.Output.OutputEvent'
to model the keyboard, mouse and webbrowser. Assumes that the server connects to webbrowser which sends information in a JSON formatted String('EventLoop.EventProcessor.IOMessage').
-}
module EventLoop.Main(start) where

import EventLoop.EventProcessor
import EventLoop.Input.InputEvent
import EventLoop.Output.OutputEvent
import EventLoop.Json
         
-- | High-level function to start an eventloop. The eventloop takes an 'EventLoop.Input.InputEvent' and outputs an 'EventLoop.Output.OutputEvent'.
--   Starting place for the example implementation of the eventloop. It takes a variable of type a to hold information in between handler calls.
start :: (a -> InputEvent -> ([OutputEvent], a)) -- ^ Eventhandler from 'EventLoop.Input.InputEvent' to a list of 'EventLoop.Output.OutputEvent'. Also takes a variable of type a that holds the current state of information. Returns a changed variable of type a that will be called with next handler call.
      -> a                                       -- ^ The begin state of variable a.
      -> IO()
start handler beginstate = eventloop handler' beginstate
                        where
                            handler' = changeTypes handler

-- | Low-level eventloop to High-Level eventloop converter. Changes 'IOMessage's to 'InputEvent's and 'OutputEvent's.
changeTypes :: (a -> InputEvent -> ([OutputEvent], a)) -> a -> IOMessage -> ([IOMessage], a)
changeTypes f state message = (map toJsonMessage oEvents, state')
                    where
                        iEvent = fromJsonMessage message
                        (oEvents, state') = f state iEvent