
source("modules/Loading/R/dates2load.R")
source("modules/Loading/R/get_timeidx.R")
source("modules/Loading/R/check_latlon.R")

dims_multimodel <- function(recipe) {
  
  archive <- read_yaml("conf/archive.yml")$esarchive
  ref.name <- recipe$Analysis$Datasets$Reference$name
  if (tolower(recipe$Analysis$Horizon) == 'seasonal') {
    exp.name <- recipe$Analysis$Datasets$System$models
  } else if (tolower(recipe$Analysis$Horizon) == 'decadal') {
    exp.name <- sapply(recipe$Analysis$Datasets$System$models, '[[', 'name')
  } else {stop('Multimodel not implemented for this horizon.')}
  store.freq <- recipe$Analysis$Variables$freq
  variable <- strsplit(recipe$Analysis$Variables$name, ", | |,")[[1]]
  exp_descrip <- archive$System[[exp.name[1]]]
  reference_descrip <- archive$Reference[[ref.name]]
  createFrom <- str_to_title(recipe$Analysis$Datasets$Multimodel$createFrom)
  sdates <- dates2load(recipe, recipe$Run$logger)
  
  lats.min <- recipe$Analysis$Region$latmin
  lats.max <- recipe$Analysis$Region$latmax
  lons.min <- recipe$Analysis$Region$lonmin
  lons.max <- recipe$Analysis$Region$lonmax
  circularsort <- check_latlon(lats.min, lats.max, lons.min, lons.max)
  
  if (recipe$Analysis$Variables$freq == "monthly_mean") {
    split_multiselected_dims = TRUE
  } else {
    split_multiselected_dims = FALSE
  }
  
  # Find the saved data directory
  recipe$Run$output_dir <- file.path(recipe$Run$output_dir, "outputs", createFrom)
  if (tolower(recipe$Analysis$Output_format) == "scorecards") {
    hcst_start <- recipe$Analysis$Time$hcst_start
    hcst_end <- recipe$Analysis$Time$hcst_end
    shortdate <- substr(recipe$Analysis$Time$sdate, start = 1, stop = 2)
    filename <- paste0("scorecards_$model$_", ref.name, "_$var$_$file_date$_",
                       hcst_start, "-", hcst_end, "_s", shortdate, ".nc")
  } else {
    filename <- "$var$_$file_date$.nc"
  }

  hcst.path <- file.path(get_dir(recipe = recipe, variable = variable[1]), filename)
  hcst.path <- gsub(variable[1], "$var$", hcst.path)
  hcst.path <- gsub('Multimodel', "$model$", hcst.path)
  fcst.path <- obs.path <- hcst.path

  # Load hindcast 
  #-------------------------------------------------------------------
  hcst <- Start(dat = hcst.path,
                var = variable,
                file_date = sdates$hcst,
                model = gsub('\\.','',exp.name),
                time = 'all',
                latitude = 'all',
                latitude_reorder = Sort(),
                longitude = 'all',
                longitude_reorder = circularsort,
                synonims = list(latitude = c('lat', 'latitude'),
                                longitude = c('lon', 'longitude'),
                                ensemble = c('member', 'ensemble')),
                ensemble = 'all',
                metadata_dims = 'var',
                largest_dims_length = TRUE,
                return_vars = list(latitude = 'dat',
                                   longitude = 'dat',
                                   time = 'file_date'),
                split_multiselected_dims = split_multiselected_dims,
                retrieve = FALSE)

  dim.hcst <- attr(hcst,'Dimensions')
  
  # Load forecast
  #-------------------------------------------------------------------
  if (!is.null(recipe$Analysis$Time$fcst_year)) {
    fcst <- Start(dat = fcst.path,
                  var = variable,
                  file_date = sdates$fcst,
                  model = gsub('\\.','',exp.name),
                  time = 'all',
                  latitude = 'all',
                  latitude_reorder = Sort(),
                  longitude = 'all',
                  longitude_reorder = circularsort,
                  synonims = list(latitude = c('lat', 'latitude'),
                                  longitude = c('lon', 'longitude'),
                                  ensemble = c('member', 'ensemble')),
                  ensemble = 'all',
                  metadata_dims = 'var',
                  largest_dims_length = TRUE,
                  return_vars = list(latitude = 'dat',
                                     longitude = 'dat',
                                     time = 'file_date'),
                  split_multiselected_dims = split_multiselected_dims,
                  retrieve = FALSE)
    
    dim.fcst <- attr(fcst,'Dimensions')
    
  } else {
    dim.fcst <- NULL
  }
  
  return(list(dim.hcst = dim.hcst, dim.fcst = dim.fcst))
}
