{-# LANGUAGE RecordWildCards #-}

module Network.Shelob.Connection where

import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified GHC.IO.Handle as H

import           Network.Shelob.Types

handleToConnection :: H.Handle -> Connection
handleToConnection h = Connection { .. }
  where connRead n   = BS.hGet h n
        connReadLine = BS.hGetLine h
        connWrite bs = LBS.hPut h bs
        connClose    = H.hClose h

connReadContents :: Connection -> IO BS.ByteString
connReadContents conn = do
  buf <- connRead conn 1024
  if buf == ""
    then connClose conn >> return buf
    else BS.append buf `fmap` connReadContents conn
