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

#' Plot log reduction
#' 
#' Boxplot of log reduction for each barrier according to population exposed and pathogen Name
#' @param scenario with log reduction column obtained with simulate_treatment function
#' @importFrom tibble tibble
#' @importFrom purrr map
#' @importFrom tidyr unnest
#' @import ggplot2
#' @import colorspace
#' @return plots
#' 
#' @export
#' @examples
#' library(purrr)
#' library(tidyr)
#' library(dplyr)
#'
#' scenario_test <- create_scenario(system.file("input_1culture_2pop.xlsx", package = "ambre"))
#'
#' scenario_conc <- inflow_concentration(scenario = scenario_test,
#'  pathogenName = c("Campylobacter jejuni", "Norovirus"))
#'
#' scenario_volume <-
#'   scenario_conc |>                     
#'   mutate(
#'     volume = map(
#'       .x = config,                                         
#'       .f = ~ simulate_exposure(config = .x)              
#'     )
#'   )
#'
#' scenario_dose_ini <- initial_dose_calculation(scenario_volume)
#'
#' scenario_scheme <- update_treatment_scheme(scenario_dose_ini)
#'
#' scenario_with_logreduc_and_co <- scenario_scheme |> 
#'   mutate( log_reduction = map(config, simulate_treatment))
#'
#' plot_logreduction(scenario_with_logreduc_and_co)
plot_logreduction <- function(scenario){
  plot_log <- tibble(
        logReduction = map(
              scenario$log_reduction,
              ~ .x$events_long$logreduction
              ),
        PopulationName = scenario$PopulationName,
        PathogenGroup = map(
              .x = scenario$log_reduction,
              .f = ~ .x$events_long$PathogenGroup
              ),
        CropName = scenario$CropName,
        TreatmentName = map(scenario$log_reduction, 
                            ~.x$events_long$TreatmentName
                            )
        )
  
  plot_log_long <- plot_log |> unnest(c(logReduction, TreatmentName, PathogenGroup))
  
  n_treat <- length(unique(plot_log_long$TreatmentName))
  
  plots <- plot_log_long |>
    split(~ PathogenGroup) |>
    imap(function(df, pathogen){

      ggplot(df, aes(x = PopulationName, y = logReduction, fill = TreatmentName)) +
    geom_boxplot()+
    facet_grid(~CropName)+
    scale_fill_manual(
      values = rainbow_hcl(n_treat)
    ) +
    theme_minimal() +
    labs(title = pathogen, 
         x = "Population exposed",
        y = "log reduction",
        fill = "Barrier name")+
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
    })

  
  return(plots)
    
}
