module OSCSystem where

import Sound.OSC.Transport.FD
import Sound.OSC.Transport.FD.UDP

import Data.Monoid ((<>))
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad

import qualified Eventing as E
import Messages

oscServer :: Int -> E.EventBus DX200Msg -> IO ()
oscServer port eventBus =
  let
    f fd = forever (incomingOSCHandler fd eventBus)
    t = udpServer "0.0.0.0" port
  in
    do
      void (forkIO (withTransport t f))
      putStrLn $ "Running OSC server on port " <> show port

incomingOSCHandler :: (Transport t) => t -> E.EventBus DX200Msg -> IO ()
incomingOSCHandler t eventBus = do
    msg <- recvMessage t
    maybe (return ()) writeMsg msg
  where
    writeMsg m = atomically $ writeTQueue (E.queue eventBus) (OSCMsg m)

