#'Gets the corresponding dates or indices according
#'to the start dates, min. and max. leadtimes and 
#'time frequency.
# 
#'The leadtimes are returned as dates in POSIXct format,
#'so that they can be read by Start().
#'The leadtimes are defined by months
#'
#'@param sdates vector containind the start dates
#'@param ltmin first leadtime
#'@param ltmax last leadtime
#'@param time_freq time frequency ("monthly_mean" or "daily_mean" or "daily")
#'@param ncores number of cores to use for parallel computation

get_forecast_times <- function(sdates, ltmin, ltmax, 
                               time_freq="monthly_mean",
                               ncores = 1) {

  if (time_freq %in% c("daily_mean", "daily")) {

    sdates <- ymd(sdates)
    idx_min <- sdates + months(ltmin - 1)
    idx_max <- sdates + months(ltmax) - days(1)

    day_seq <- seq(idx_min[1], idx_max[1], by = 'days')
    if (any("0229" %in% (format(day_seq, "%m%d")))) {
      time_length <- as.integer(idx_max[1]-idx_min[1])
    } else {
      time_length <- as.integer(idx_max[1]-idx_min[1]+1)
    }
    indxs <- array(numeric(), c(file_date = length(sdates),
                                time = time_length))
                                #syear = length(sdates),
                                #sday = 1, sweek = 1,

    for (sdate in 1:length(sdates)) {
      day_seq <- seq(idx_min[sdate], idx_max[sdate], by = 'days')
      indxs[sdate,] <- day_seq[!(format(day_seq, "%m%d") == "0229")]
    }
    indxs <- as.POSIXct(indxs*86400, 
                        tz = 'UTC', origin = '1970-01-01')
    lubridate::hour(indxs) <- 12 
    lubridate::minute(indxs) <- 01
    dim(indxs) <- c(file_date = length(sdates),
                    time = time_length)

  } else if (time_freq == "monthly_mean") {
    # idx_min <- ltmin
    # idx_max <- ltmax
    # indxs <- indices(idx_min:idx_max)
    indxs <- Apply(sdates,
                   margins = list(x = "syear"),
                   fun = function(x, idx_min, idx_max) {
                     x <- as.POSIXct(x, format = "%Y%m%d", tz = "UTC") %m+% months(idx_min:idx_max)
                     return(as.array(x))
                   },
                   output_dims = c("time"),
                   idx_min = ltmin - 1,
                   idx_max = ltmax - 1,
                   ncores = ncores
                   )[[1]]
    indxs_dims <- dim(indxs)
    indxs <- as.POSIXct(indxs, origin = "1970-01-01", tz = "UTC")
    lubridate::day(indxs) <- round(days_in_month(indxs)/2 + 1)
    lubridate::hour(indxs) <- 12
    lubridate::minute(indxs) <- 01
    dim(indxs) <- indxs_dims
    names(dim(indxs)) <- c("time", "file_date")
  }

  # TODO: 6 hourly case
  #idx1 <- (sdates + months(ltmin-1) - sdates)*4
  #idx2 <- idx1 + ndays*4 - 1

  return(indxs)
}
