## TODO: Separate by time aggregation
## TODO: Build a default path that accounts for:
## variable, system, reference, start date and region name

get_filename <- function(dir, recipe, var, date, agg, file.type) {
  # This function builds the path of the output file based on directory,
  # variable, forecast date, startdate, aggregation, forecast horizon and
  # type of metric/forecast/probability.
  
  if (tolower(recipe$Analysis$Horizon) == "subseasonal") {
    shortdate <- format(as.Date(as.character(date), "%Y%m%d"), "%V")
    dd <- "week"
  } else {
    shortdate <- format(as.Date(as.character(date), "%Y%m%d"), "%m")
    dd <- "month"
  }

  if (tolower(recipe$Analysis$Horizon) == "decadal") {
    # to not save the month and day in the filename (needed for the multimodel)
    date <- substr(date,1,4)
    # for the models initialised in January - it may be better to do this in save_* functions
    archive <- read_yaml(paste0("conf/archive_decadal.yml"))$esarchive
    exp.name <- recipe$Analysis$Datasets$System$name
    if (exp.name != 'Multimodel' && archive$System[[exp.name]]$initial_month == 1){
      date <- as.character(as.numeric(date)-1)
    }
  }
  
  switch(tolower(agg),
	 "region" = {gg <- "-region"},
         "global" = {gg <- ""})

  system <- gsub('.','', recipe$Analysis$Datasets$System$name, fixed = T)
  reference <- gsub('.','', recipe$Analysis$Datasets$Reference$name, fixed = T)

  if (tolower(recipe$Analysis$Output_format) == 'scorecards') {
    # Define output dir name accordint to Scorecards format
    dict <- read_yaml("conf/output_dictionaries/scorecards.yml")
    # Get necessary names
    hcst_start <- recipe$Analysis$Time$hcst_start
    hcst_end <- recipe$Analysis$Time$hcst_end

    switch(file.type,
	   "skill" = {type_info <- "-skill_"},
	   "corr"  = {type_info <- "-corr_"},
	   "exp"   = {type_info <- paste0("_", date, "_")},
	   "obs"   = {type_info <- paste0("-obs_", date, "_")},
	   "percentiles" = {type_info <- "-percentiles_"},
	   "probs" = {type_info <- paste0("-probs_", date, "_")},
	   "bias"  = {type_info <- paste0("-bias_", date, "_")})

    # Build file name
    file <- paste0("scorecards_", system, "_", reference, "_",
		   var, type_info, hcst_start, "-", hcst_end, "_s", shortdate)
  } else {
    
    if (tolower(recipe$Analysis$Horizon) == "decadal") {
      shortdate_aux <- ''
    } else {
      shortdate_aux <- paste0("_", dd, shortdate)
    }
      
    switch(file.type,
  	   "skill" = {file <- paste0(var, gg, "-skill", shortdate_aux)},
  	   "corr"  = {file <- paste0(var, gg, "-corr", shortdate_aux)},
  	   "exp"   = {file <- paste0(var, gg, "_", date)},
  	   "obs"   = {file <- paste0(var, gg, "-obs_", date)},
  	   "percentiles" = {file <- paste0(var, gg, "-percentiles",shortdate_aux)},
  	   "probs" = {file <- paste0(var, gg, "-probs_", date)},
  	   "bias"  = {file <- paste0(var, gg, "-bias_", date)})
  }
  return(paste0(dir, file, ".nc"))
}

