## 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 (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"
  }

  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, "_")},
     # new
     "rps_syear" = {type_info <- paste0("rps_syear")},
     "rps_clim_syear" = {type_info <- paste0("rps_clim_syear")},
     "crps_syear" = {type_info <- paste0("crps_syear")},
     "crps_clim_syear" = {type_info <- paste0("crps_clim_syear")},
     "crps" = {type_info <- paste0("crps")},
     "mean_bias" = {type_info <- paste0("mean_bias")},
	   {type_info <- paste0(file.type)})

    # Build file name
    file <- paste0("scorecards_", system, "_", reference, "_",
		   var,  "_",type_info, "_", hcst_start, "-", hcst_end, "_s", shortdate)
  } else {
    switch(file.type,
  	   "skill" = {file <- paste0(var, gg, "-skill_", dd, shortdate)},
  	   "corr"  = {file <- paste0(var, gg, "-corr_", dd, shortdate)},
  	   "exp"   = {file <- paste0(var, gg, "_", date)},
  	   "obs"   = {file <- paste0(var, gg, "-obs_", date)},
  	   "percentiles" = {file <- paste0(var, gg, "-percentiles_", dd, 
  	          			 shortdate)},
  	   "probs" = {file <- paste0(var, gg, "-probs_", date)},
  	   "bias"  = {file <- paste0(var, gg, "-bias_", date)})
  }
  return(paste0(dir, file, ".nc"))
}

