
context("Subseasonal weekly data")


# source("modules/Loading/Loading.R")
# source("modules/Units/Units.R")
# source("modules/Calibration/Calibration.R")
# source("modules/Skill/Skill.R")
# source("modules/Anomalies/Anomalies.R")
# source("modules/Saving/Saving.R")
source("modules/Visualization/Visualization.R")
source("modules/Loading/Loading.R")
source("modules/Saving/R/get_dir.R")


recipe_file <- "tests/recipes/recipe-subseasonal_visualization.yml"
recipe <- prepare_outputs(recipe_file, disable_checks = FALSE)

# Load datasets
suppressWarnings({invisible(capture.output(
  data <- Loading(recipe)
))})

# Units transformation
# suppressWarnings({invisible(capture.output(
#   data <- Units(recipe, data)
# ))})

# Compute skill metrics
# suppressWarnings({invisible(capture.output(
#   skill_metrics <- Skill(recipe, data)
# ))})

# Compute percentiles and probability bins
# suppressWarnings({invisible(capture.output(
#   probabilities <- Probabilities(recipe, data)
# ))})

## outdir <- get_dir(recipe = recipe, variable = data$hcst$attrs$Variable$varName)
outdir <- "./tests/out-logs/"

output_conf <- read_yaml("modules/Visualization/output_size.yml",
                         eval.exp = TRUE)$region




# ------- TESTS --------


test_that("1. Loading", {
  
  expect_equal(
    is.list(data),
    TRUE
  )
  
  expect_true(
    all(c("hcst", "fcst", "obs") %in% names(data))
  )
  
  expect_equal(
    class(data$hcst),
    "s2dv_cube"
  )
  
  expect_equal(
    class(data$fcst),
    "s2dv_cube"
  )
  
  expect_equal(
    class(data$obs),
    "s2dv_cube"
  )
  
  expect_equal(
    names(data$hcst),
    c("data", "dims", "coords", "attrs")
  )
  
  expect_equal(
    names(data$hcst),
    names(data$fcst)
  )
  
  expect_equal(
    names(data$hcst),
    names(data$obs)
  )
  
  expect_equal(
    dim(data$hcst$data),
    c(dat = 1, var = 1, sday = 3, sweek = 5, syear = 5, time = 4, latitude = 10, longitude = 21, ensemble = 12)
  )
  
  expect_equal(
    dim(data$fcst$data),
    c(dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 4, latitude = 10, longitude = 21, ensemble = 48)
  )
  
  expect_equal(
    dim(data$hcst$attrs$Dates),
    c(sday = 3, sweek = 5, syear = 5, time = 4)
  )
  
})


# ----------------------



pfm_elements <- plot_forecast_map(recipe = recipe, fcst = data$fcst,
                                  mask = NULL, dots = NULL,
                                  outdir = outdir, output_conf = output_conf,
                                  return_elements = TRUE)


test_that("2. Test plot_forecast_map() metadata.", {
  
  expect_equal(
    pfm_elements$latitude[1],
    -4.251954, 
    tolerance = 0.001
  )
  
  expect_equal(
    pfm_elements$longitude[1],
    -9.375,
    tolerance = 0.001
  )
  
  expect_equal(
    pfm_elements$system_name,
    "NCEP CFSv2"
  )
  
  expect_equal(
    pfm_elements$start_date,
    20240104
  )
  
  expect_equal(
    pfm_elements$init_date,
    20240104
  )
  
  expect_equal(
    pfm_elements$palette,
    "RdBu"
  )
  
  expect_equal(
    pfm_elements$brks[1:3],
    c(-30, -25, -20)
  )
  
  expect_equal(
    pfm_elements$cols[1:3],
    c(-30, -25, -20)
  )
  
  expect_equal(
    pfm_elements$toptitle,
    "NCEP CFSv2 / 2 Metre Temperature\nEnsemble median / Issued on 04-01-2024\nValid from 29-01 to 04-02 of 2024"
  )
  
  expect_equal(
    pfm_elements$labels$time_labels[1],
    "Valid from 08-01 to 14-01 of "
  )
  
  expect_equal(
    pfm_elements$labels$years[1],
    2024
  )
  
  expect_equal(
    pfm_elements$fileout,
    "./tests/out-logs/forecast_ensemble_median-20240104_ft04.png"
  )
  
})

# ----------------------

## Skill module not adapted for subseasonal data yet
skill_metrics_dims <- c(var = 1, time = 4, latitude = 10, longitude = 21)
bool_array <- array(rep(c(TRUE, FALSE), length.out = prod(skill_metrics_dims)), dim = skill_metrics_dims)
skill_metrics_subs <- list(
  rpss = bool_array,
  rpss_significance = bool_array
)

pm_elements <- plot_metrics(recipe = recipe, data_cube = data$hcst,
                            metrics = skill_metrics_subs, outdir = outdir,
                            output_conf = output_conf,
                            return_elements = TRUE)


test_that("3. Test plot_metrics() metadata.", {
  
  expect_equal(
    pm_elements$latitude[1],
    -4.251954, 
    tolerance = 0.001
  )
  
  expect_equal(
    pm_elements$longitude[1],
    -9.187988, ## gata$fcst$coords$longitude[1] (pfm)  !=  data$hcst$coords$longitude[1] (pm)
    tolerance = 0.001
  )
  
  expect_equal(
    pm_elements$system_name,
    "NCEP CFSv2"
  )
  
  expect_equal(
    pm_elements$start_date,
    20240104
  )
  
  expect_equal(
    pm_elements$brks[1:3],
    c(-1, -0.8, -0.6)
  )
  
  expect_equal(
    pm_elements$cols[1:3],
    c(-1, -0.8, -0.6)
  )
  
  expect_equal(
    pm_elements$toptitle,
    "NCEP CFSv2 / 2 Metre Temperature \n RPSS  /  Issued on  04-01-2024  /  1999-2003 \n Valid from 29-01 to 04-02 of 2024"
  )
  
  expect_equal(
    pm_elements$nominal_startdate_caption,
    as.Date("2024-01-04")
  )
  
  expect_equal(
    pm_elements$forecast_time_caption,
    "Forecast week: 04"
  )
  
  expect_equal(
    pm_elements$fileout,
    "./tests/out-logs/rpss-20240104_ft04.png"
  )

})


# ----------------------

## Probabilities module not adapted for subseasonal data yet

data$probs$fcst ## Not loading from recipe?

pmlt_elements <- plot_most_likely_terciles(recipe = recipe,
                                           fcst = data$fcst,
                                           probabilities = probabilities_subs,
                                           outdir = outdir,
                                           output_conf = output_conf,
                                           return_elements = TRUE)




# multiprobs_global <- readRDS("~/SUNSET_RS_GIT/sunset/Ari_multiprobs_global.Rds")

# probabilities_dims <- c(var = 1, syear = 1, time = 4, bin = 1, latitude = 10, longitude = 21)
# set.seed(42)  # For reproducibility
# prob_b33      <- array(runif(prod(probabilities_dims), min = 0, max = 0.3), dim = probabilities_dims)
# prob_33_to_66 <- array(runif(prod(probabilities_dims), min = 0.3, max = 0.7), dim = probabilities_dims)
# prob_a66      <- array(runif(prod(probabilities_dims), min = 0.7, max = 1), dim = probabilities_dims)
# prob_b10      <- array(runif(prod(probabilities_dims), min = 0, max = 0.1), dim = probabilities_dims)
# prob_10_to_90 <- array(runif(prod(probabilities_dims), min = 0.1, max = 0.9), dim = probabilities_dims)
# prob_a90      <- array(runif(prod(probabilities_dims), min = 0.9, max = 1), dim = probabilities_dims)
# 
# probs_fcst <- list(
#   prob_b33      = prob_b33,
#   prob_33_to_66 = prob_33_to_66,
#   prob_a66      = prob_a66,
#   prob_b10      = prob_b10,
#   prob_10_to_90 = prob_10_to_90,
#   prob_a90      = prob_a90
# )
# 
# probabilities_subs <- list(
#   probs_fcst = probs_fcst
# )

