module FortyTwo.Prompts.Password (password) where
import System.Console.ANSI (cursorBackward, clearFromCursorToScreenEnd, setCursorColumn, clearFromCursorToLineEnd)
import Control.Monad (unless)
import FortyTwo.Renderers.Password (renderPassword, hideLetters)
import FortyTwo.Renderers.Question (renderQuestion)
import FortyTwo.Constants (emptyString, enterKey, delKey)
import FortyTwo.Utils
password :: String -> IO String
password question = do
putStrLn emptyString
renderQuestion question emptyString emptyString
putStr " "
flush
noBuffering
answer <- loop emptyString
restoreBuffering
setCursorColumn 0
clearFromCursorToLineEnd
renderQuestion question emptyString $ hideLetters answer
return answer
loop :: String -> IO String
loop pass = do
noEcho
renderPassword pass
key <- getKey
unless (null pass) $ do
cursorBackward $ length pass
clearFromCursorToScreenEnd
res <- handleEvent pass (if length key > 1 then emptyString else key)
restoreEcho
return res
handleEvent :: String -> String -> IO String
handleEvent pass key
| key == enterKey = return pass
| key == delKey =
if null pass then return loop emptyString pass
else return loop emptyString (init pass)
| otherwise = loop $ pass ++ key