## FROM s2dv_cube object to list compatible with downscaleR
## FOR DOWNSCALING, Coordinates 'x' and 'y' must be given in ascending order
## DImensions of the downscaleR array stored in the list should be "time", "lat", "lon"
## obj is the s2dv_cube object to be converted. dim names are the dim names of the s2dv_cube object
## Author: Eren Duzenli
## Requires: ClimProjDiags, CSTools, others??
#' obj: s2dv_cube object
#' time_dim: character string, name of the time dimension
#' sdate_dim: character string, name of the sdate dimension
#' lat_dim: character string, name of the latitudinal dimension
#' lon_dim: character string, name of the longitudinal dimension
#' memb_dim: character string, name of the ensemble dimension
#' copy_data: boolean, return the data array as well as the metadata (TRUE)
#'            or only the metadata (FALSE)

s2dv_cube2Climate4R <- function(obj, time_dim = "time", sdate_dim = "syear", 
                                lat_dim = "latitude", lon_dim = "longitude",
                                memb_dim = "ensemble", copy_data = TRUE) {
  # Initialize list
  DUM <- list() 
  # Merge sdate and time dimensions and subset data
  dum <- MergeDims(obj$data, merge_dims = c(time_dim, sdate_dim), 
                   rename_dim= "time")
  dum <- Subset(dum, along = c("time", lat_dim, lon_dim, memb_dim), drop = "non-selected", 
	                       indices = list(1:dim(dum)["time"], 1:dim(dum)[lat_dim], 
                                              1:dim(dum)[lon_dim],1:dim(dum)[memb_dim]))
  attributes(dum)["dimensions"] <- list(c("time", "lat", "lon","member"))
  attributes(dum)["dim"] <- list(as.numeric(dim(dum)))
  names(dim(dum)) <- NULL
  # If copy_data is FALSE, set $Data as NULL to avoid data duplication
  if (copy_data) {
    DUM$Data <- dum
  } else {
    DUM$Data <- NULL
  }
  # Set xyCoords
  DUM$xyCoords$x <- as.numeric(obj$coords$lon)
  DUM$xyCoords$y <- as.numeric(obj$coords$lat)
  # Set Dates
  if (!is.null(obj$attrs$time_bounds)) {
    DUM$Dates$start <- format(obj$attrs$time_bounds[[1]], 
                              format = "%Y-%m-%d %Z")
    DUM$Dates$end <- format(obj$attrs$time_bounds[[2]], 
                            format = "%Y-%m-%d %Z")
  } else {
    # If no time_bounds available, use Dates?
    DUM$Dates$start <- format(obj$attrs$Dates,
                              format = "%Y-%m-%d %Z")
    DUM$Dates$end <- format(obj$attrs$Dates,
                            format = "%Y-%m-%d %Z")
  }
  # Set Variable
  ## TODO: Retrieve level from s2dv_cube object (it currently does not include this information)
  DUM$Variable <- list(varName = obj$attrs$Variable$varName, level = NULL)
  attributes(DUM$Variable)$names <- list("varName", "level")
  attributes(DUM$Variable)$units <- get(DUM$Variable$varName,
                                        obj$attrs$Variable$metadata)$units
  attributes(DUM$Variable)$longname <- get(DUM$Variable$varName, 
                                           obj$attrs$Variable$metadata)$long_name
  ## TODO: What is the parameter use_dictionary for?
  attributes(DUM$Variable)$use_dictionary <- FALSE
  ## TODO: Include variable description in s2dv_cube? or just use long name?
  attributes(DUM$Variable)$description <- get(DUM$Variable$varName,
                                              obj$attrs$Variable$metadata)$long_name
  attributes(DUM$Variable)$daily_agg_cellfun <- get(DUM$Variable$varName, 
                                                    obj$attrs$Variable$metadata)$cell_methods
  ## TODO: Include condition for daily data
  attributes(DUM$Variable)$monthly_agg_cellfun <- "none" ## this func is only for daily
  ## TODO: What is the parameter verification_time for?
  attributes(DUM$Variable)$verification_time <- "DD" ## ?
  # Set Members
  member_names <- paste0("Member_", 1:length(obj$coords[[memb_dim]]))
  DUM$Members <- member_names
  ## TODO: Change and get values from somewhere else, or include them in s2dv_cube
  attributes(DUM$Members)$dataset <- obj$attrs$Datasets
  attributes(DUM$Members)$source <- "BSC-CNS"
  attributes(DUM$Members)$URL <- NULL
  # Set InitializationDates
  file_dates <- data$hcst$attrs$load_parameters$dat1$file_date[[1]]
  dim(file_dates) <- NULL
  attributes(file_dates) <- NULL
  DUM$InitializationDates <- rep(list(file_dates), length(member_names))
  names(DUM$InitializationDates) <- member_names
  
  return(DUM)
}
