# Print a summary of the loaded data for the user, for each object.
# data_cube: An s2dv_cube returned by one of the functions in Auto-S2S
# recipe: The Auto-S2S recipe as returned by read_yaml()

## TODO: Adapt to daily/subseasonal cases
## TODO: Add check for missing files/NAs by dimension

data_summary <- function(data_cube, recipe) {
  # Get name, leadtime months and date range
  object_name <- deparse(substitute(data_cube))
  if (recipe$Analysis$Variables$freq == "monthly_mean") {
    date_format <- "%b %Y"
  } else if (recipe$Analysis$Variables$freq %in% c("daily", "daily_mean")) {
    date_format <- "%b %d %Y"
  }
  months <- unique(format(as.Date(data_cube$attrs$Dates), format = '%B'))
  months <- paste(as.character(months), collapse=", ")
  sdate_min <- format(min(as.Date(data_cube$attrs$Dates)),
                      format = date_format)
  sdate_max <- format(max(as.Date(data_cube$attrs$Dates)),
                      format = date_format)
  # Log the summary
  info(recipe$Run$logger, "DATA SUMMARY:")
  info(recipe$Run$logger, paste(object_name, "months:", months))
  info(recipe$Run$logger, paste(object_name, "range:", sdate_min, "to", 
                                 sdate_max))
  info(recipe$Run$logger, paste(object_name, "dimensions:"))
  # Use capture.output() and for loop to display results neatly
  output_string <- capture.output(dim(data_cube$data))
  for (i in output_string) {
    info(recipe$Run$logger, i)
  }
  # Print statistical summary of the data for every variable
  info(recipe$Run$logger, paste0("Statistical summary of the data in ",
                                 object_name, ":"))
  for (var_index in 1:data_cube$dims[['var']]) {
    variable_name <- data_cube$attrs$Variable$varName[var_index]
    variable_units <- data_cube$attrs$Variable$metadata[[variable_name]]$units
    info(recipe$Run$logger,
         paste0("Variable: ", variable_name,
                " (units: ", variable_units, ")"))
    output_string <- capture.output(summary(Subset(data_cube$data,
                                                   along = "var",
                                                   indices = var_index)))
    for (i in output_string) {
      info(recipe$Run$logger, i)
    }
  }
  info(recipe$Run$logger, "---------------------------------------------")
  invisible(gc())
}
