{-|
Module      : GossipProtocol
Description : Implements some utility functions that are used throughout the implementation.
Copyright   : (c) Jesper Kuiper, 2021
                  Leander van Boven, 2021
                  Ramon Meffert, 2021
License     : BSD3
-}

module Util 
  ( -- * Coloured printing
    putStrFgc
  , putStrLnFgc
  -- * Messaging
  , printInvalidAction
  , printGraphComplete
  -- * Pretty BDD to graph saving
  , writeToSvgGraph
  )
where

import System.Console.ANSI
import System.IO
import PrintableBdd
import Data.HasCacBDD.Visuals

-- | Prints a message that an action is invalid for the current context. 
printInvalidAction :: Char -> IO ()
printInvalidAction :: Char -> IO ()
printInvalidAction Char
action = do
  Color -> String -> IO ()
putStrFgc Color
Red String
"Invalid action: "
  Color -> String -> IO ()
putStrFgc Color
Blue [Char
action]
  String -> IO ()
putStrLn String
" is not a valid action in the current context."

-- | Prints a message that the current graph is complete, i.e. every agent is an expert. 
printGraphComplete :: IO ()
printGraphComplete :: IO ()
printGraphComplete = do
  Color -> String -> IO ()
putStrLnFgc Color
Green String
"\n!!! Graph complete !!!"
  String -> IO ()
putStrLn String
"Everybody is an expert (i.e. every agent knows the secrets of all other agents)."

-- | Prints the given message in a given colour. 
putStrFgc :: Color -> String -> IO ()
putStrFgc :: Color -> String -> IO ()
putStrFgc Color
c String
s = do
  [SGR] -> IO ()
setSGR [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
c]
  String -> IO ()
putStr String
s
  [SGR] -> IO ()
setSGR [SGR
Reset]

-- | Prints the given mesage with a new line in a given colour. 
putStrLnFgc :: Color -> String -> IO ()
putStrLnFgc :: Color -> String -> IO ()
putStrLnFgc Color
c String
s = do
  [SGR] -> IO ()
setSGR [ConsoleLayer -> ColorIntensity -> Color -> SGR
SetColor ConsoleLayer
Foreground ColorIntensity
Vivid Color
c]
  String -> IO ()
putStrLn String
s
  [SGR] -> IO ()
setSGR [SGR
Reset]

-- | Save a Bdd in its graph structure as an SVG file. Uses the dot language, for which Graphviz needs to be installed. 
writeToSvgGraph :: String -> Bdd -> IO ()
writeToSvgGraph :: String -> Bdd -> IO ()
writeToSvgGraph String
s Bdd
b = Bdd -> IO String
svgGraph (Bdd -> Bdd
bdd Bdd
b) IO String -> (String -> IO ()) -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> String -> IO ()
writeFile String
s