#'Save metadata chunks to an .Rds file
#'
#'When using Compute(), the metric names and the metadata of each chunk need 
#'to be saved separately so that they can be pieced back together once all the
#'data is retrieved into memory. This function saves the necessary information
#'for each chunk into a temporary folder \code{output_dir/tmp/<module>/}.
#'
#'@param recipe The SUNSET recipe as retrieved by \code{prepare_outputs()} or 
#'  \code{read_atomic_recipe()}.
#'@param metrics A list of named arrays containing the metrics to be saved.
#'@param data_cube An s2dv_cube used to compute the metrics, with the relevant
#'  metadata.
#'@param module The name of the module in string format.
#'@param nchunks Vector of chunks used in Compute().
#'@export

save_metadata_chunks <- function(recipe, metrics, data_cube, module, nchunks) {
  # Retrieve original dimensions
  dimensions <- names(dim(metrics[[1]]))
  # Bind list into an array
  metrics <- abind(metrics, along = 0)
  # Retrieve dimname attributes
  metric_names <- dimnames(metrics)[[1]]
  ## TODO: Force module into Camel Case
  if (!is.null(recipe$Run$atomic_name)) {
    tmp_dir <- file.path(recipe$Run$output_dir, "outputs", "tmp",
                         recipe$Run$atomic_name, module)
  } else {
    tmp_dir <- file.path(recipe$Run$output_dir, "outputs", "tmp", module)
  }
  # Save metric names (only done once)
  if (!dir.exists(tmp_dir)) {
    dir.create(tmp_dir, recursive = TRUE)
    saveRDS(metric_names, file.path(tmp_dir, "metric_names.Rds"))
  }
  # Add 'metric' dimension to array and restore attributes
  names(dim(metrics)) <- c("metric", dimensions)
  # Save s2dv_cube metadata
  metadata_filename <- "metric_metadata"
  for (chunk in names(nchunks)) {
    metadata_filename <- paste0(metadata_filename, "_", chunk, "_", nchunks[[chunk]])
  }
  metadata_filename <- paste0(metadata_filename, ".Rds")
  data_cube$data <- NULL
  saveRDS(data_cube, file.path(tmp_dir, metadata_filename))
  return(metrics)
}
