module Sound.OpenSoundControl.Transport.Monad.ByteString (run, ) where

import qualified Sound.OpenSoundControl.Transport.Monad as TM

import Sound.OpenSoundControl.OSC (encodeOSC, OSC, )

import Control.Monad.Trans.Reader (ReaderT, runReaderT, ask, )
import Control.Monad.Trans (lift, )

import qualified Data.ByteString.Lazy as B
import qualified Data.Binary.Put as Put

newtype T a = Cons (ReaderT OSC Put.PutM a)
   deriving (Functor, Monad)

instance TM.C T where
   send msg = Cons $ lift $
      let b = encodeOSC msg
      in  Put.putWord32be (fromIntegral (B.length b)) >>
          Put.putLazyByteString b

   recv = Cons ask

{- |
Write sent messages to a ByteString.
All 'recv' calls are answered with @msg@.
run :: OSC -> T () -> B.ByteString
run msg (Cons m) = Put.runPut (runReaderT m msg)