## 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_mod <- 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
  if (copy_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), drop = "non-selected", 
	                       indices = list(1:dim(dum)["time"], 1:dim(dum)[lat_dim], 
                                              1:dim(dum)[lon_dim]))
  } else{
    dum<-array(0)
  }
  
  attributes(dum)["dimensions"] <- list(c("member","time", "lat", "lon"))

  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 <- obj$hcst$attrs$load_parameters$dat1$file_date[[1]] #???????????
  dim(file_dates) <- NULL
  attributes(file_dates) <- NULL


  DUM$InitializationDates<-list()

  #DUM$InitializationDates <- rep(list(file_dates), length(member_names))
  for (i in 1:length(DUM$Members)){

  name<-DUM$Members[i]
  nums<-obj$attrs$load_parameters$dat1$sdate[[1]]
  d<-nums[1:length(nums)]
  sdates <- list(format(as.Date(d, "%Y%m%d"), format = "%Y-%m-%d")) #Removed %Z
  DUM$InitializationDates[name]<-sdates
  
  }
  
  return(DUM)
}
