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

#' Create random distribution based on configuration file
#' 
#' This function does the same thing as kwb.utils::generate_random_values(),
#' but it is bundled with *ambre* to avoid a hard dependency on the
#' unmaintained package.
#' 
#' @param config as retrieved by config_read()
#' @param number_of_repeatings how often should the random distribution with the
#' same parameters be generated (default: 1)
#' @param number_of_events number of events
#' @param debug print debug information (default: TRUE)
#' @return list random distributions based on configuration file
#' @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)
#' @export
#' @examples
#' # Example usage of generate_random_values
#' # Create a sample config object
#' config <- list(
#'   type = "norm",
#'   value = 10,
#'   min = 5,
#'   max = 15,
#'   mean = 10,
#'   sd = 2,
#'   meanlog = log(10),
#'   sdlog = 0.5,
#'   mode = 10
#' )
#'
#' # Call generate_random_values with the sample config
#' result <- generate_random_values(
#'   config = config,
#'   number_of_repeatings = 2,
#'   number_of_events = 10,
#'   debug = FALSE
#' )
#'
#' # Print the results
#' cat("Simulated events:")
#' print(result$events)
#'
#' cat("Parameters used for simulation:")
#' print(result$paras)
generate_random_values <- function(
  config, number_of_repeatings = 1, number_of_events, debug = TRUE
) 
{
  default <- function(x, default) {
    if (is.na(x)) default else x
  }
  
  # Set defaults based on min/max for function create_random_distribution() if
  # values are missing
  if (config$type == "norm") {
    config$mean <- default(config$mean, (config$max + config$min) / 2)
    config$sd <- default(config$sd, sd(c(config$mean, config$max)) / 2)
  }

  if (config$type == "lognorm") {
    config$meanlog <- default(config$meanlog, log((config$min + config$max) / 2))
    config$sdlog <- default(config$sdlog, sd(log((c(config$min, config$max)))))
  }

  if (config$type == "triangle") {
    if (is.na(config$mode)) {
      if (config$min == config$max) {
        catIf(debug,
          "Distribution set from 'triangle' to 'uniform' because 'min'", 
          "equals 'max'\n"
        )
        config$type <- "uniform"
      } else {
        config$mode <- (config$min + config$max) / 2
      }
    }
  }
  
  create_random_distribution(
    type = config$type,
    number_of_repeatings = number_of_repeatings,
    number_of_events = number_of_events,
    value = config$value,
    min = config$min,
    max = config$max,
    mean = config$mean,
    sdev = config$sd,
    meanlog = config$meanlog,
    sdlog = config$sdlog,
    mode = config$mode,
    debug = debug
  )
}
