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

#' Helper function: distribution repeater
#' 
#' This function does the same thing as kwb.utils::distribution_repeater(),
#' but it is bundled with *ambre* to avoid a hard dependency on the
#' unmaintained package.
#' 
#' @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 (a single positive integer, >= 1)
#' @param func distribution function to be repeated (e.g. runif, rlnorm, rnorm)
#' @param ... further parameters passed to func
#' @importFrom stats setNames
#' @importFrom tidyr gather
#' @importFrom dplyr mutate select
#' @return data.frame with columns repeatID, eventID and values
#' @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
#'  distribution_repeater(
#'    number_of_repeatings = 2,
#'    number_of_events = 10,
#'    func = runif,
#'    min = 1,
#'    max = 10
#' )
distribution_repeater <- function(
  number_of_repeatings = 10, number_of_events = 365, func, ...
)
{
  if (
    ! is.numeric(number_of_events) || length(number_of_events) != 1 ||
    is.na(number_of_events) || number_of_events < 1
  ) {
    stop("number_of_events must be a single positive integer (>= 1)")
  }

  seq_repeatings <- seq_len(number_of_repeatings)

  repl <- vapply(
    seq_repeatings,
    function(i) func(n = number_of_events, ...),
    FUN.VALUE = numeric(number_of_events)
  )

  # vapply() collapses the result to a plain vector when number_of_events == 1;
  # coerce back to a matrix so every case flows through the same pipeline and
  # the function always returns the documented long data.frame.
  repl <- matrix(repl, nrow = number_of_events)

  repl |>
    as.data.frame() |>
    cbind(eventID = seq_len(number_of_events)) |>
    stats::setNames(c(seq_repeatings, "eventID")) |>
    tidyr::gather(key = "repeatID", value = "values", -.data$eventID) |>
    dplyr::mutate(repeatID = as.integer(.data$repeatID)) |>
    dplyr::select(.data$repeatID, .data$eventID, .data$values)
}
