# Seasonal monthly data

## TO REMOVE ## ****************************************************************
## setwd("/home/Earth/abatalla/SUNSET_RS_GIT/sunset") ## dev
## library(testthat)
# ******************************************************************************

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")


recipe_file <- "./tests/recipes/recipe-seasonal_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)
))})

# Calibrate data
suppressWarnings({invisible(capture.output(
  data <- Calibration(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)
))})



# ------- 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 = 1, sweek = 1, syear = 4, time = 1, latitude = 12, longitude = 15, ensemble = 25)
  )
  
  expect_equal(
    dim(data$fcst$data),
    c(dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 12, longitude = 15, ensemble = 51)
  )
  
  expect_equal(
    dim(data$hcst$attrs$Dates),
    c(sday = 1, sweek = 1, syear = 4, time = 1)
  )
  
})



# --- SNAPSHOT TESTS ---

Sys.setenv(TESTTHAT_EDITION = "3")

outdir <- "./tests/testthat/_snaps/seasonal_visualization/"

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


# plot_ensemble_mean

save_fun_1 <- function(...) {
  path <- "./tests/testthat/_snaps/seasonal_visualization/" ## dev: "./_snaps/"
  do.call(plot_ensemble_mean, list(...))
  return(path)
}

rpss_sig <- skill_metrics$rpss_significance
rpss_sig[1, 1, 1:6, ] <- TRUE

test_that("2. Snapshot checks: plot_ensemble_mean", {
  
  expect_snapshot_file(
    paste0(save_fun_1(recipe = recipe, fcst = data$fcst,
                    outdir = outdir, output_conf = output_conf), 
           "forecast_ensemble_mean-20230601_ft01.png"),
    name = "forecast_ensemble_mean-20230601_ft01.png")
  
  expect_snapshot_file(
    paste0(save_fun_1(recipe = recipe, fcst = data$fcst, dots = rpss_sig,
                      outdir = outdir, output_conf = output_conf),
           "forecast_ensemble_mean-20230601_enscordots_ft01.png"),
    name = "forecast_ensemble_mean-20230601_enscordots_ft01.png")
  
  expect_snapshot_file(
    paste0(save_fun_1(recipe = recipe, fcst = data$fcst, mask = rpss_sig,
                      outdir = outdir, output_conf = output_conf),
           "forecast_ensemble_mean-20230601_enscormask_ft01.png"),
    name = "forecast_ensemble_mean-20230601_enscormask_ft01.png")
})


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

# plot_metrics

save_fun_2 <- function(...) {
  path <- "./tests/testthat/_snaps/seasonal_visualization/"
  do.call(plot_metrics, list(...))
  return(path)
}

skill_metrics$rpss_significance[1, 1, 1:6, ] <- TRUE

test_that("3. Snapshot checks: plot_metrics", {
  
  expect_snapshot_file(
    paste0(save_fun_2(recipe = recipe, data_cube = data$hcst,
                      metrics = skill_metrics, outdir = outdir,
                      significance = FALSE, output_conf = output_conf), 
           "rpss-june_ft01.png"),
    name = "rpss-june_ft01.png")
  
  expect_snapshot_file(
    paste0(save_fun_2(recipe = recipe, data_cube = data$hcst,
                      metrics = skill_metrics, outdir = outdir,
                      significance = TRUE, output_conf = output_conf), 
           "rpss-june_ft01_mask.png"),
    name = "rpss-june_ft01_mask.png")
  
})


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

# plot_most_likely_terciles

save_fun_3 <- function(...) {
  path <- "./tests/testthat/_snaps/seasonal_visualization/"
  do.call(plot_most_likely_terciles, list(...))
  return(path)
}

test_that("4. Snapshot checks: plot_most_likely_terciles", {

  expect_snapshot_file(
    paste0(save_fun_3(recipe = recipe, fcst = data$fcst,
                      probabilities = probabilities,
                      mask = NULL, dots = NULL,
                      outdir = outdir, output_conf = output_conf),
           "forecast_most_likely_tercile-20230601_ft01.png"),
    name = "forecast_most_likely_tercile-20230601_ft01.png")

  expect_snapshot_file(
    paste0(save_fun_3(recipe = recipe, fcst = data$fcst,
                      probabilities = probabilities,
                      mask = rpss_sig, dots = NULL,
                      outdir = outdir, output_conf = output_conf),
           "forecast_most_likely_tercile-20230601_rpssmask_ft01.png"),
    name = "forecast_most_likely_tercile-20230601_rpssmask_ft01.png")
  
  expect_snapshot_file(
    paste0(save_fun_3(recipe = recipe, fcst = data$fcst,
                      probabilities = probabilities,
                      mask = NULL, dots = rpss_sig,
                      outdir = outdir, output_conf = output_conf),
           "forecast_most_likely_tercile-20230601_rpssdots_ft01.png"),
    name = "forecast_most_likely_tercile-20230601_rpssdots_ft01.png")

})

# Remove the pdf files
unlink(list.files(outdir, pattern = "\\.pdf$", full.names = TRUE))

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

# To test locally:
# testthat::test_file("./tests/testthat/test-seasonal_visualization.R")


# How the snapshot tests work:
# the "save_fun" part  creates the new plot, by default a pdf. It needs a name
# It is then compared to the png in the "name" part. 
# If they are different, a png with the plot created in "save_fun" is created with the name from the "name" part + ".new".
# The first part needs a name so that it can be compared. Otherwise an empty ".new" png is created. 
# Summarizing: now a pdf and a png (from the png) are created, If the png is the same as the one that exists, the test passes. Then the pdf is removed.
