{-|
Module:             Text.IO
Description:        IO for Text handling.
Copyright:          © 2016 All rights reserved.
License:            GPL-3
Maintainer:         Evan Cofsky <>
Stability:          experimental
Portability:        POSIX
-}

module Text.IO (
    readFile,
    writeFile,
    appendFile,
    getLine,
    putStr,
    putStrLn,
    hGetLine,
    hPutStr,
    hPutStrLn,
    readLines,
    writeLines
    ) where

import Lawless
import Prelude.Unicode (())
import qualified Data.Text.IO as TIO
import Data.Text (Text)
import System.Path
import System.Path.IO (Handle, hIsEOF)
import Machine

readFile  (MonadIO m)  AbsRelFile  m Text
readFile = liftIO  TIO.readFile  toString

writeFile  (MonadIO m)  AbsRelFile  Text  m ()
writeFile f t = liftIO $ TIO.writeFile (toString f) $ t

appendFile  (MonadIO m)  AbsRelFile  Text  m ()
appendFile f t = liftIO $ TIO.appendFile (toString f) t

putStr  (MonadIO m)  Text  m ()
putStr = liftIO  TIO.putStr

putStrLn  (MonadIO m)  Text  m ()
putStrLn = liftIO  TIO.putStrLn

hPutStr  (MonadIO m)  Handle  Text  m ()
hPutStr h = liftIO  TIO.hPutStr h

hPutStrLn  (MonadIO m)  Handle  Text  m ()
hPutStrLn h = liftIO  TIO.hPutStrLn h

getLine  (MonadIO m)  m Text
getLine = liftIO TIO.getLine

hGetLine  (MonadIO m)  Handle  m Text
hGetLine = liftIO  TIO.hGetLine

-- * Machines

-- | Read lines of 'Text' from a 'Handle' until $EOF$ is reached.
readLines    (m  *  *). (MonadIO m)  Handle  SourceT m Text
readLines h = repeatedly $ ifM (liftIO $ hIsEOF h) stop (hGetLine h ≫= yield)

-- | Write lines of 'Text' to a 'Handle' until there are no
-- more. Forwards them on.
writeLines   (m  *  *). (MonadIO m)  Handle  ProcessT m Text Text
writeLines h = autoM (\l  hPutStrLn h l  return l)