context("get_plot_time_labels.R")

source("tools/libs.R")
source("modules/Loading/R/get_timeidx.R")
source("modules/Loading/R/dates2load.R")
###########################################

sdates <- list()
sdates$fcst <- "20250501"
dim(sdates$fcst) <- c(sday = 1, sweek = 1, syear = 1)
sdates$hcst <- paste0(1993:2016, "0501")
dim(sdates$hcst) <- c(sday = 1, sweek = 1, syear = length(1993:2016))

testthat("1. Seasonal daily, 6 months", {
  ltmin <- 1
  ltmax <- 6
  time_freq <- "daily_mean"

  idxs <- list()
  idxs$hcst <- get_timeidx(sdates = sdates$hcst,
                           ltmin = ltmin,
                           ltmax = ltmax,
                           time_freq = time_freq)

  idxs$fcst <- get_timeidx(sdates = sdates$fcst,
                           ltmin = ltmin,
                           ltmax = ltmax,
                           time_freq = time_freq)
  # Results
  expect_equal(
    dim(idxs$hcst),
    c(file_date = 24, time = 184)
  )
  expect_equal(
    idxs$hcst[1],
    "1993-05-01 12:01:00 UTC"
  )
  expect_equal(
    idxs$hcst[24, 2],
    "2016-05-02 12:01:00 UTC"
  )
  expect_equal(
    idxs$hcst[4, 91],
    "1996-07-30 12:01:00 UTC"
  )
  expect_equal(
    dim(idxs$fcst),
    c(file_date = 1, time = 184)
  )
  expect_equal(
    idxs$fcst[1],
    "2025-05-01 12:01:00 UTC"
  )
  expect_equal(
    idxs$fcst[1, 2],
    "2025-05-02 12:01:00 UTC"
  )
  expect_equal(
    idxs$fcst[1, 91],
    "2025-07-30 12:01:00 UTC"
  )
})


sdates <- list()
sdates$fcst <- "20231201"
dim(sdates$fcst) <- c(sday = 1, sweek = 1, syear = 1)
sdates$hcst <- paste0(1993:1996, "1201")
dim(sdates$hcst) <- c(sday = 1, sweek = 1, syear = length(1993:1996))

testthat("2. Seasonal monthly, 2 months, end of year", {
  ltmin <- 1
  ltmax <- 2
  time_freq <- "monthly_mean"

  idxs <- list()
  idxs$hcst <- get_timeidx(sdates = sdates$hcst,
                           ltmin = ltmin,
                           ltmax = ltmax,
                           time_freq = time_freq)

  idxs$fcst <- get_timeidx(sdates = sdates$fcst,
                           ltmin = ltmin,
                           ltmax = ltmax,
                           time_freq = time_freq)
  # Results
  expect_equal(
    dim(idxs$hcst),
    c(time = 2, file_date = 4)
  )
  expect_equal(
    idxs$hcst[1, ],
    c("1993-12-16 12:01:00 UTC", "1994-12-16 12:01:00 UTC",
      "1995-12-16 12:01:00 UTC", "1996-12-16 12:01:00 UTC")
  )
  expect_equal(
    idxs$hcst[2, ],
    c("1994-01-16 12:01:00 UTC", "1995-01-16 12:01:00 UTC",
      "1996-01-16 12:01:00 UTC", "1997-01-16 12:01:00 UTC")
  )
  expect_equal(
    dim(idxs$fcst),
    c(time = 2, file_date = 1)
  )
  expect_equal(
    idxs$fcst[1, ],
    "2023-12-16 12:01:00 UTC"
  )
  expect_equal(
    idxs$fcst[2, ],
    "2023-01-16 12:01:00 UTC"
  )
})
