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/Intbc.R')
require(testthat)
require(CSTools)
require(multiApply)
require(s2dv)

context("Generic tests")
test_that("Sanity checks", {
  expect_error(
    CST_Intbc(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)) 

  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 <- suppressWarnings(s2dv_cube(data = obs, lat = obs_lats, lon = obs_lons))

  expect_error(
    supressWarnings(CST_Intbc(exp = exp, obs = obs, bc_method = 'cal'),
    paste0("Parameter 'method_remap' must be a character vector indicating the ",
      "interpolation method. Accepted methods are con, bil, bic, nn, con2")))

  obs2 <- rnorm(180)
  dim(obs2) <- c(lat = 12, lon = 15, sdate = 1)
  obs2 <- suppressWarnings(s2dv_cube(data = obs2, lat = obs_lats, lon = obs_lons))  

  expect_warning(
    CST_Intbc(exp = exp, obs = obs2, int_method = 'bil', bc_method = 'sbc', 
              target_grid = 'r1280x640'),
    'Simple Bias Correction should not be used with only one observation. Returning NA.')
 
  exp2 <- rnorm(100)
  dim(exp2) <- c(member = 1, lat = 4, lon = 5, sdate = 5, time  = 1)
  exp2 <- suppressWarnings(s2dv_cube(data = exp2, lat = exp_lats, lon = exp_lons))

  expect_error( 
    suppressWarnings(CST_Intbc(exp = exp2, obs = obs, int_method = 'bil', bc_method = 'cal', 
                              target_grid = 'r1280x640'), 'Calibration must not be used 
                              with only one ensemble member.'))	 

  d1 <- suppressWarnings(CST_Intbc(exp = exp, obs = obs, int_method = 'bil', bc_method = 'sbc', 
                                   target_grid = 'r640x320'))
  expect_equal(round(d1$exp$data[, 1, 1, 1, 1], 2), c(-0.40, 0.08, -0.23, 0.38, -0.03))

  d2 <- suppressWarnings(CST_Intbc(exp = exp, obs = obs, int_method = 'bil', bc_method = 'cal', 
                                   target_grid = 'r640x320'))
  expect_equal(round(d2$exp$data[, 1, 1, 1, 1], 2), c(-0.47, -0.03, -0.31, 0.24, -0.13))

  d3 <- suppressWarnings(CST_Intbc(exp = exp, obs = obs, int_method = 'bil', bc_method = 'qm', 
                        target_grid = 'r640x320'))
  expect_equal(round(d3$exp$data[, 1, 1, 1, 1], 2), c(0.00, 0.00, 0.00, 0.33, 0.00))
  })
    



