# For each chunking dimension, retrieve the metadata for each chunk from its
# .Rds file and put the pieces together, generating the complete coordinates,
# dimensions and attributes of the resulting s2dv_cube.
# 
# tmp_dir: string, The temporary directory where the metadata files are stored.
# chunks: named list of chunking dimensions with the amount of chunks for each.
# array_dims: vector containing the dimensions of the final array.

retrieve_metadata <- function(tmp_dir, chunks, array_dims) {
  ## TODO: add array_dims parameter
  ## For each chunking dimension
  # Build metadata file pattern:
  metadata_file_pattern <- "skill_metadata"
  for (chunk in sort(names(chunks))) {
    metadata_file_pattern <- paste0(metadata_file_pattern, "_", chunk, "_*")
  }
  metadata_file_pattern <- paste0(metadata_file_pattern, ".Rds")
  metadata_files <- list.files(path = tmp_dir, pattern = glob2rx(metadata_file_pattern))
  metadata <- readRDS(paste0(tmp_dir, metadata_files[1]))
  # Piece together variable info
  if ("var" %in% names(chunks)) {
    # $attrs
    for (i in 2:chunks[["var"]]) {
      metadata_chunk <- readRDS(paste0(tmp_dir,
                                       gsub("var_1", paste0("var_", i),
                                            metadata_files[1])))
      var_name <- metadata_chunk$attrs$Variable$varName
      metadata$attrs$Variable$varName <- c(metadata$attrs$Variable$varName,
                                           var_name)
      metadata$attrs$Variable$metadata <- c(metadata$attrs$Variable$metadata,
                                            metadata_chunk$attrs$Variable$metadata[var_name])
    }
    # $coords
    metadata$coords$var <- metadata$attrs$Variable$varName
    dim(metadata$coords$var) <- c(var = length(metadata$coords$var))
    attr(metadata$coords$var, "values") <- TRUE
    attr(metadata$coords$var, "indices") <- FALSE
    # $dims
    metadata$dims["var"] <- array_dims["var"]
  }
  # Piece together time info
  if ("time" %in% names(chunks)) {
    dates_dims <- dim(metadata$attrs$Dates)
    for (i in 2:chunks[["time"]]) {
      metadata_chunk <- readRDS(paste0(tmp_dir,
                                       gsub("time_1", paste0("time_", i),
                                            metadata_files[1])))
      metadata$attrs$Dates <- c(metadata$attrs$Dates, metadata_chunk$attrs$Dates)
    }
    time_dim_length <- array_dims[["time"]]
    dim(metadata$attrs$Dates) <- c(dates_dims[names(dates_dims) != "time"],
                                   time = time_dim_length)
    metadata$coords$time <- seq(1, time_dim_length)
    dim(metadata$coords$time) <- c(time = time_dim_length)
    attr(metadata$coords$time, "indices") <- TRUE
    #$dims
    metadata$dims["time"] <- array_dims["time"]
  }
  # Piece together lon/lat info
  if ("latitude" %in% names(chunks)) {
    # $attrs
    ## TODO: Preserve attributes
    for (i in 2:chunks[["latitude"]]) {
      metadata_chunk <- readRDS(paste0(tmp_dir,
                                       gsub("latitude_1", paste0("latitude_", i),
                                            metadata_files[1])))
      metadata$attrs$Variable$metadata$latitude <- c(metadata$attrs$Variable$metadata$latitude,
                                                     metadata_chunk$attrs$Variable$metadata$latitude)
    }
    # $coords
    metadata$coords$latitude <- metadata$attrs$Variable$metadata$latitude
    dim(metadata$coords$latitude) <- c(latitude = length(metadata$coords$latitude))
    # $dims
    metadata$dims["latitude"] <- array_dims["latitude"]
  }

  if ("longitude" %in% names(chunks)) {
    # $attrs
    ## TODO: Preserve attributes
    for (i in 2:chunks[["longitude"]]) {
      metadata_chunk <- readRDS(paste0(tmp_dir,
                                       gsub("longitude_1", paste0("longitude_", i),
                                            metadata_files[1])))
      metadata$attrs$Variable$metadata$longitude <- c(metadata$attrs$Variable$metadata$longitude,
                                                      metadata_chunk$attrs$Variable$metadata$longitude)
    }
    # $coords
    metadata$coords$longitude <- metadata$attrs$Variable$metadata$longitude
    dim(metadata$coords$longitude) <- c(longitude = length(metadata$coords$longitude))
    # $dims
    metadata$dims["longitude"] <- array_dims["longitude"]
  }
  return(metadata)
}
