# WARNING - Generated by {fusen} from dev/flat_kwb_simulate_inflow.Rmd: do not edit by hand # nolint: line_length_linter.

#' Print Debug Messages Before and After Running Code
#'
#' This function does the same thing as kwb.utils::catIf(),
#' but it is bundled with *ambre* to avoid a hard dependency on the 
#' unmaintained package.
#' 
#' @param messageText text to be printed before running the code
#' @param expr expressions to be run. Enclose more than one expression in
#'   curly braces
#' @param newLine integer controlling new lines. 0: no extra new line, 1:
#'   new line after \code{messageText}, 2: new line after "ok.", 3: new line
#'   after both, \code{messageText} and "ok."
#' @param dbg logical. If \code{FALSE}, output is suppressed.
#' @param log_time logical. If \code{TRUE}, the time elapsed during the 
#'   evaluation of \code{expr} is printed.
#' @return This function returns the evaluation of \code{expr}. The result is
#'   returned invisibly so that the result of an assignment as the last 
#'   expression in \code{exprt} does not show up on the console.
#' @references
#'   Sonnenberg H (2024). kwb.utils: General Utility Functions Developed at KWB. R package version 0.15.0
#'   URL: \url{https://github.com/kwb-r/kwb.utils}
#'   (MIT Licence)
#' @noRd
#' @examples
#' for (newLine in 0:3) {
#'   catAndRun("work hard", newLine = newLine, {
#'      cat("hard\nworking\n")
#'     })
#'
#'   cat("here.\n\n")
#' } 
catAndRun <- function(
  messageText = "Running code", expr, newLine = 2L, dbg = TRUE, log_time = TRUE
)
{
  catIf(dbg, messageText, "... ")
  
  catNewLineIf(dbg && bitwAnd(newLine, 1))
  
  start_time <- Sys.time()
  
  result <- eval(expr, envir = -1)

  catIf(dbg, "ok. ")
  
  dt <- Sys.time() - start_time
  
  catIf(dbg && log_time, sprintf("(%0.2f %s) ", dt, attr(dt, "units")))
  
  catNewLineIf(dbg && bitwAnd(newLine, 2))
  
  invisible(result)
}
