## TODO: Documentation

CST_ChangeDimName <- function(data, original_dimnames, final_dimnames) {
  if (!inherits(data, "s2dv_cube")) {
    stop("Parameter 'data' must be an object of class 's2dv_cube'")
  }
  if (!(length(original_dimnames) == length(final_dimnames))) {
    stop("The number of dimension names in 'final_dimnames' must be the same
         as in 'original_dimnames'")
  }
  ## TODO: Add check to verify that all original_dimnames are present in the array
  for (index in 1:length(original_dimnames)) {
    original_name <- original_dimnames[index]
    final_name <- final_dimnames[index]
    # Step 1: Change dims and data
    names(data$dims)[which(names(data$dims) == original_name)] <- final_name
    dim(data$data) <- data$dims
    # Step 2: Change coords
    names(data$coords)[which(names(data$coords) == original_name)] <- final_name
    # Step 3: Change attrs
    # 3.1 - Dates
    if (original_name %in% names(dim(data$attrs$Dates))) {
      names(dim(data$attrs$Dates))[which(names(dim(data$attrs$Dates)) 
                                         == original_name)] <- final_name
    }
    # 3.2 - Variable metadata
    if (original_name %in% names(data$attrs$Variable$metadata)) {
      names(data$attrs$Variable$metadata)[which(names(data$attrs$Variable$metadata) 
                                                == original_name)] <- final_name
    }
    # 3.3 - Source files
    if (original_name %in% names(dim(data$attrs$source_files))) {
      names(dim(data$attrs$source_files))[which(names(dim(data$attrs$source_files))
                                                == original_name)] <- final_name
    }
  }
  return(data)
}

