set.seed(1)
source('/esarchive/scratch/jramon/GitLab_jramon/downscaling/csdownscale/R/Interpolation.R')
source('/esarchive/scratch/jramon/GitLab_jramon/downscaling/csdownscale/R/Utils.R')
source('/esarchive/scratch/jramon/GitLab_jramon/downscaling/csdownscale/R/Intlr.R')
require(testthat)
require(CSTools)
require(multiApply)
require(s2dv)

context("Generic tests")
test_that("Sanity checks", {
  expect_error(
    CST_Intlr(exp = 1),
    "Parameter 'exp' must be of the class 's2dv_cube'")
  
  exp <- rnorm(500)
  dim(exp) <- c(member = 5, lat = 4, lon = 5, sdate = 5, time  = 1)
  exp_lons <- 1:5
  exp_lats <- 1:4
  exp <- suppressWarnings(s2dv_cube(data = exp, lat = exp_lats, lon = exp_lons)) 

  expect_error(CST_Intlr(exp = exp), "argument \"obs\" is missing, with no default")

  obs <- rnorm(900)
  dim(obs) <- c(lat = 12, lon = 15, sdate = 5, time = 1)
  obs_lons <- seq(1,5, 4/14)
  obs_lats <- seq(1,4, 3/11)
  obs <- s2dv_cube(data = obs, lat = obs_lats, lon = obs_lons)

  expect_error(
    CST_Intlr(exp = exp, obs = obs, lr_method = 1),
    "Parameter 'lr_method' must be of the class 'character'")

  expect_error(
    CST_Intlr(exp = exp, obs = obs, lr_method = "basic"),
    paste0("Parameter 'int_method' must be a character vector indicating the interpolation ",
           "method. Accepted methods are con, bil, bic, nn, con2"))

  expect_error(
    CST_Intlr(exp = exp, obs = obs, lr_method = "large-scale", int_method = "bil", target_grid = 'r1280x640',
              region = c(1, 5, 1, 4)),
    "The large-scale predictors must be passed through the parametre 'predictors'")

  expect_error(
    CST_Intlr(exp = exp, obs = obs, lr_method = "large-scale", int_method = "bil", target_grid = 'r1280x640',
              region = c(1, 5, 1, 4), predictors = 1),
    "Parameter 'predictors' must be of the class 'array'")

  expect_error(
    CST_Intlr(exp = exp, obs = obs, int_method = "bil", target_grid = 'r1280x640', region = c(1, 5, 1, 4),
              lr_method = "a"),
    "a method is not implemented yet")

  d1 <- CST_Intlr(exp = exp, obs = obs, lr_method = "basic", int_method = "bil", target_grid = 'r1280x640')
  expect_equal(round(d1$data[, 1, 1, 1, 1], 2), c(-0.70, -0.20, 0.56, 0.87, 0.60))

  d2 <- CST_Intlr(exp = exp, obs = obs, lr_method = "4nn")
  expect_equal(round(d2$data[, 1, 1, 1, 1], 2), c(0.08, 1.08, 0.80, 0.47, -0.52))

  ind_rdm <- array(rnorm(30), dim = c(sdate = 5, member = 3, vars = 2))
  d3 <- CST_Intlr(exp = exp, obs = obs, lr_method = "large-scale", int_method = "bil", target_grid = 'r1280x640',
        region = c(1, 5, 1, 4), predictors = ind_rdm)
  expect_equal(round(d3$data[, 1, 1, 1, 1], 2), c(-0.26, -0.92, 0.70, 0.74, 0.86))
  })
    



