#'Gets the corresponding dates or indices according
#'to the start dates, min. and max. leadtimes and 
#'time frequency.
# 
#'The leadtimes are defined by months
#'Ex. 20201101 with leadtimes 1-4 corresponds to 
#'the forecasting times covering November to february
#'
#'@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")

get_timeidx <- function(sdates, ltmin, ltmax, 
                        time_freq="monthly_mean") {

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

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

  return(indxs)
}
