module Observer where

import IO
import Utils
import IOExts

data T = Mk
  { talkTo    :: Handle
  , alive     :: Mutable Bool
  }


r `sendStr` msg   = (talkTo r `hPutStr` msg) `catch` \e -> kill r
r `sendStrLn` msg = (talkTo r `hPutStrLn` msg) `catch`  
                                                    \e -> kill r
r `send` msg      = r `sendStr` show msg 
r `sendLn` msg    = r `sendStrLn` show msg
  
kill :: T -> IO ()
kill r = (r `set` alive) False >> hClose (talkTo r) `catch` \e -> return ()


create h = do
  h `hSetBuffering` LineBuffering
  aliveR <- new True
  return $ Observer.Mk
    { Observer.talkTo = h
    , Observer.alive  = aliveR
    }