#'Read requested dates from recipe and return array of file dates to be loaded
#'
#'The purpose of this function is to read the recipe configuration data for 
#'Auto-S2S workflows, retrieve the start and end dates for the hindcast and
#'the forecast dates, and return two arrays containing the requested dates, to
#'be passed to the Start() call. If no fcst date is provided, it returns an
#'empty object.
#'
#'@param recipe Auto-S2S configuration recipe as returned by read_yaml()
#'@param logger object of class logger containing log output file information
#'
#'@return a list of two arrays containing file dates for hcst and fcst
#'
#'@export

library(lubridate)

dates2load <- function(recipe, logger) {

  temp_freq <- recipe$Analysis$Variables$freq
  system_name <- recipe$Analysis$Datasets$System$name
  recipe <- recipe$Analysis$Time
  # hcst dates
  file_dates <- paste0(strtoi(recipe$hcst_start):strtoi(recipe$hcst_end),
                       recipe$sdate)

  # Note: UKMO models are always missing the start date of January 1993.
  # This piece of code removes that date from the start dates.
  UKMO_MODELS <- c("UK-MetOffice-Glosea600", "UK-MetOffice-Glosea601",
                   "UKMO-System602")
  if ((system_name %in% UKMO_MODELS) && ("19930101" %in% file_dates)) {
    file_dates <- file_dates[-(which(file_dates == '19930101'))]
    warn(logger,
         paste("January 1993 start date is not available for", system_name,
               "and has been removed from the list of start dates."))
  }

  # Add dimensions to the vector
  if (temp_freq == "monthly_mean") {
    file_dates <- .add_dims(file_dates)
  }
  # fcst dates (if fcst_year empty it creates an empty object)
  if (! is.null(recipe$fcst_year)) {
    file_dates.fcst <- paste0(recipe$fcst_year, recipe$sdate)
    if (temp_freq == "monthly_mean") {
      file_dates.fcst <- .add_dims(file_dates.fcst)
    }
  } else {
    file_dates.fcst <- NULL
    info(logger,
         paste("fcst_year empty in the recipe, creating empty fcst object..."))
  }
  return(list(hcst = file_dates, fcst = file_dates.fcst))
}

# adds the correspondent dims to each sdate array
.add_dims <- function(data) {

  default_dims <- c(sday = 1, sweek = 1, syear = length(data))
  default_dims[names(dim(data))] <- dim(data)
  dim(data) <- default_dims
  return(data)
}

