module Mischief.ECS.Stdin where

import Control.Monad.IO.Class
import GHC.IO.Handle
import Mischief.ECS.World
import System.IO
import Prelude hiding (read)

init :: System ()
init :: System ()
init = IO () -> System ()
forall a. IO a -> System a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> System ()) -> IO () -> System ()
forall a b. (a -> b) -> a -> b
$ do
  Handle -> BufferMode -> IO ()
hSetBuffering Handle
stdin BufferMode
NoBuffering
  Handle -> Bool -> IO ()
hSetEcho Handle
stdin Bool
False

read :: System String
read :: System String
read = do
  ready <- IO Bool -> System Bool
forall a. IO a -> System a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> System Bool) -> IO Bool -> System Bool
forall a b. (a -> b) -> a -> b
$ Handle -> IO Bool
hReady Handle
stdin
  if ready
    then do
      c <- liftIO getChar
      ([c] ++) <$> read
    else do
      return []

readLast :: System (Maybe Char)
readLast :: System (Maybe Char)
readLast = do
  r <- System String
read
  return $ case r of
    [] -> Maybe Char
forall a. Maybe a
Nothing
    String
x -> Char -> Maybe Char
forall a. a -> Maybe a
Just (Char -> Maybe Char) -> Char -> Maybe Char
forall a b. (a -> b) -> a -> b
$ String -> Char
forall a. HasCallStack => [a] -> a
last String
x