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

#' Concentration reduction matrix calculation
#' 
#' Calculate the difference of achieve concentration in effluent according to regulation 
#' @param scenario data.frame with log_reduction column obtained with simulate_treatment function
#' @param regulation data.frame regulation table to compare to simulation results
#' @importFrom formattable formattable
#' @importFrom purrr map
#' @import dplyr
#' @importFrom tidyr unnest pivot_wider
#' @return formattable 
#' 
#' @export
#' @examples
#' \donttest{
#' library(dplyr)
#' library(purrr)
#' scenario_example <- create_scenario(system.file("input_1culture_2pop.xlsx", 
#'                                                 package = "ambre"))
#'
#' scenario_exposure <- scenario_example |> mutate(
#'      volume = map(
#'          .x = config,                                         
#'          .f = ~ simulate_exposure(config = .x)))
#'
#' scenario_patho <- update_pathogen(scenario = scenario_exposure, 
#'                                   pathoName = c("Rotavirus", "Campylobacter jejuni", "Norovirus"))
#' concentration = map(.x = scenario_patho$config,
#'                    .f= ~ simulate_inflow(.x))
#' scenario_concentration <- scenario_patho |> mutate(inflow_concentration = concentration)
#' scenario_ini_dose <- initial_dose_calculation(scenario = scenario_concentration)
#'
#' scenario_barrier <- update_treatment_scheme(scenario = scenario_ini_dose, initial_situation = TRUE)
#'
#' scenario_barrier$config <- purrr::pmap(
#'   list(
#'     config = scenario_barrier$config,
#'     barrierID = scenario_barrier$SupplementaryProcessID,
#'     cropHeight = scenario_barrier$CropHeight,
#'     matrixID = scenario_barrier$MatrixID,
#'     popID = scenario_barrier$PopulationID,
#'     decay = scenario_barrier$nb_day_decay
#'   ),
#'   function(config, barrierID, cropHeight, matrixID, popID, decay) {
#'
#'     if (barrierID %in% c(24, 26, 27, 28) &&
#'         matrixID %in% c(3, 5)) {
#'
#'       update_logreduction_specific_barrier(
#'         config = config,
#'         cropHeight = cropHeight,
#'         barrierID = barrierID
#'       )
#'
#'     } else if (barrierID %in% c(12)) {
#'
#'       update_logreduction_decay(
#'         config = config,
#'         cropHeight = cropHeight,
#'         barrierID = barrierID,
#'         popID = popID,
#'         nb_day_decay = decay
#'       )
#'
#'     } else if (barrierID %in% c(9,13,14,15,16,17,18,24,26,27,28)) {
#'
#'       update_logreduction_path(
#'         config = config,
#'         matrixID = matrixID,
#'         barrierID = barrierID,
#'         popID = popID
#'       )
#'
#'     } else {
#'       config
#'     }
#'   }
#' )
#'   
#' scenario_logreduction <- scenario_barrier |> 
#'     mutate(log_reduction = map(config, simulate_treatment))
#'
#' regulation_concentration <- config_ambre$regulation$regulation_value |> 
#'   dplyr::filter(Country == "France") |>
#'   dplyr::select(-c(Country, RegulationID, Reduction))
#'
#' regulation_matrix_concentration(scenario = scenario_logreduction,
#'                                 regulation = regulation_concentration)
#' }
regulation_matrix_concentration <- function(scenario, regulation){
  
  if (!"log_reduction" %in% names(scenario)) {
  stop("The log_reduction column is missing from the scenario object; run simulate_treatment function to create it")
}
 
  total_logreduction_regulation <- map(
    scenario$log_reduction,
    ~ .x$events_long |>
        filter(TreatmentID %in% 1:7) |>
        group_by(repeatID, eventID, PathogenGroup) |>
        summarise(total_logreduction = round(sum(logreduction),0), .groups = "drop")
  )
    
  scenario$log_reduction_regulation <- total_logreduction_regulation
  
  
  regulation_evaluation <- map2(.x= scenario$inflow_concentration, 
                                .y = scenario$log_reduction_regulation,
                                .f= ~left_join(.x$events, .y, by = c("repeatID", "eventID", "PathogenGroup")) |>
                          mutate(effluent = 10^(log10(inflow) - total_logreduction))
                          )
    
  
  scenario$regulation <- regulation_evaluation  
  
  abattement_concentration <- scenario |> select(CropName, regulation)
  reductionC_achieve <- map(
    abattement_concentration$regulation,
    ~ .x %>%
      group_by(PathogenGroup, PathogenName) %>%
      summarise(
        max_effluent = round(max(effluent, na.rm = TRUE),0),
        .groups = "drop"
      )
  )
  pathogen_group_C <- map(.x = reductionC_achieve, .f = ~.x$PathogenGroup)
  pathogen_name_C <- map(.x = reductionC_achieve, .f = ~.x$PathogenName)
  concentration_effluent <- map(.x = reductionC_achieve, .f = ~.x$max_effluent)
  
  abattement_concentration$PathogenGroup <- pathogen_group_C
  abattement_concentration$PathogenName <- pathogen_name_C
  abattement_concentration$reductionC_achieve <- concentration_effluent
  
  abattementC <- abattement_concentration |> select(-regulation) |> 
                                              unnest(c(PathogenGroup, PathogenName, reductionC_achieve)) |> 
                                              group_by(PathogenGroup, PathogenName, CropName) %>%
                                                summarise(
                                                  max_reductionC_achieve = round(max(reductionC_achieve, na.rm = TRUE),0),
                                                  .groups = "drop"
                                                )
  abattementC_class <- abattementC |> 
    left_join(config_ambre$regulation$regulation_crop, by = "CropName")
  
  
  abattementC_class_regulation <- abattementC_class |> 
    left_join(regulation, by= c("Class","PathogenGroup")) |>
    unique() |>
    rename(concentration_regulation = Concentration)|>
    rename(target_class = Class) |>
                          mutate(color = case_when(
                                           max_reductionC_achieve > concentration_regulation ~ "#e74c3c",
                                            max_reductionC_achieve <= concentration_regulation ~ "#2ecc71",   # vert clair
                                             TRUE         ~ "#bdbdbd"
                                          ))
  tableau_valeurC <- abattementC_class_regulation |>
    select(CropName, PathogenName, max_reductionC_achieve, target_class) |>
    rename("Crop name" = CropName) |> 
    rename("Target water class" = target_class) |>
    pivot_wider(names_from=PathogenName, values_from = max_reductionC_achieve)
  
  tableau_couleurC <- abattementC_class_regulation |>
    select(CropName, PathogenName, color, target_class) |>
    rename("Crop name" = CropName) |> 
    rename("Target water class" = target_class) |>
    pivot_wider(names_from=PathogenName, values_from = color)
  
  
  tableau_nameC <- tableau_valeurC |> select(-c("Crop name", "Target water class"))
  colonnes_pathogenesC <- names(tableau_nameC)
   
  liste_formatsC <- setNames(
    lapply(colonnes_pathogenesC, function(col) {
      format_color(tableau_couleurC[[col]])
    }),
    colonnes_pathogenesC
  )
  
  table <- formattable(tableau_valeurC, liste_formatsC)
  return(table)
    
}
