module Sound.OpenSoundControl.Transport.File (T, open, ) where

import Sound.OpenSoundControl.Transport (Transport(..), )
import Sound.OpenSoundControl.Byte (encode_u32, )
import Sound.OpenSoundControl.OSC (encodeOSC, OSC, )

import Control.Monad (liftM, )
import qualified Data.ByteString.Lazy as B
import System.IO (Handle, openBinaryFile, hClose, IOMode(WriteMode), )

-- | The File transport handle data type.
data T = Cons OSC Handle
   deriving (Eq, Show)

instance Transport T where
   send (Cons _ h) msg =
      let b = encodeOSC msg
          n = fromIntegral (B.length b)
      in  B.hPut h (B.append (encode_u32 n) b)

   recv (Cons msg _) = return msg

   close (Cons _ h) = hClose h

{- |
Open a command file.
All 'recv' calls are answered with @msg@.
open :: OSC -> FilePath -> IO T
open msg fileName =
   liftM (Cons msg) $ openBinaryFile fileName WriteMode