module Binja.Utils
  ( toBool,
    ptrToMaybe,
    Colors (..),
    getColors,
  )
where

import Binja.Types.Core
import System.IO (hIsTerminalDevice, stdout)

toBool :: CBool -> Bool
toBool :: CBool -> Bool
toBool (CBool Word8
0) = Bool
False
toBool CBool
_ = Bool
True

ptrToMaybe :: Ptr a -> Maybe (Ptr a)
ptrToMaybe :: forall a. Ptr a -> Maybe (Ptr a)
ptrToMaybe Ptr a
p
  | Ptr a
p Ptr a -> Ptr a -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr a
forall a. Ptr a
nullPtr = Maybe (Ptr a)
forall a. Maybe a
Nothing
  | Bool
otherwise = Ptr a -> Maybe (Ptr a)
forall a. a -> Maybe a
Just Ptr a
p

data Colors = Colors
  { Colors -> String -> String
red :: String -> String,
    Colors -> String -> String
green :: String -> String,
    Colors -> String -> String
yellow :: String -> String,
    Colors -> String -> String
blue :: String -> String,
    Colors -> String -> String
cyan :: String -> String,
    Colors -> String -> String
magenta :: String -> String,
    Colors -> String -> String
orange :: String -> String
  }

-- |
-- Populate Colors with:
-- * identity function
-- * color coded string
-- dependent on hIsTerminalDevice stdout
getColors :: IO Colors
getColors :: IO Colors
getColors = do
  isTty <- Handle -> IO Bool
hIsTerminalDevice Handle
stdout
  let esc :: String -> String -> String
      esc String
color String
text =
        case Bool
isTty of
          Bool
True -> String
"\ESC[" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
color String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"m" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
text String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\ESC[0m"
          Bool
False -> String
text
  pure $
    Colors
      { red = esc "38;5;196",
        green = esc "38;5;46",
        yellow = esc "38;5;226",
        blue = esc "38;5;33",
        cyan = esc "38;5;51",
        magenta = esc "38;5;201",
        orange = esc "38;5;208"
      }