module ParkBench.Terminal
  ( withTerminal,
    clearFromCursor,
    cursorUp,
    blue,
    green,
    red,
  )
where

import Control.Exception (bracket_)
import qualified Data.ByteString as ByteString
import ParkBench.Builder (Builder)
import qualified ParkBench.Builder as Builder
import ParkBench.Prelude
import System.IO (hSetEcho, stdin)

withTerminal :: IO a -> IO a
withTerminal :: IO a -> IO a
withTerminal =
  IO () -> IO () -> IO a -> IO a
forall a b c. IO a -> IO b -> IO c -> IO c
bracket_ IO ()
hideCursor IO ()
showCursor (IO a -> IO a) -> (IO a -> IO a) -> IO a -> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IO () -> IO () -> IO a -> IO a
forall a b c. IO a -> IO b -> IO c -> IO c
bracket_ (Handle -> Bool -> IO ()
hSetEcho Handle
stdin Bool
False) (Handle -> Bool -> IO ()
hSetEcho Handle
stdin Bool
True)

hideCursor :: IO ()
hideCursor :: IO ()
hideCursor =
  ByteString -> IO ()
ByteString.putStr ByteString
"\ESC[?25l"

showCursor :: IO ()
showCursor :: IO ()
showCursor =
  ByteString -> IO ()
ByteString.putStr ByteString
"\ESC[?25h"

clearFromCursor :: Builder
clearFromCursor :: Builder
clearFromCursor =
  Builder
"\ESC[0J"

cursorUp :: Int -> Builder
cursorUp :: Int -> Builder
cursorUp Int
n =
  Builder
"\ESC[" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Int -> Builder
forall a. Integral a => a -> Builder
Builder.decimal Int
n Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
"F"

blue :: Builder -> Builder
blue :: Builder -> Builder
blue Builder
s =
  Builder
"\ESC[34m" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
s Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
"\ESC[39m"

green :: Builder -> Builder
green :: Builder -> Builder
green Builder
s =
  Builder
"\ESC[32m" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
s Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
"\ESC[39m"

red :: Builder -> Builder
red :: Builder -> Builder
red Builder
s =
  Builder
"\ESC[31m" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
s Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
"\ESC[39m"