context("CSTools::CST_RFTemp tests")

##############################################

test_that("Sanity checks and simple use cases", {
  # Generate simple synthetic data
  t <- rnorm(2 * 6 * 6 * 2 * 3 * 4) * 10 + 273.15 + 10
  dim(t) <- c(dataset = 2, member = 2, sdate = 3, ftime = 4, lat = 6, lon = 6)
  lon <- seq(4, 9, 1)
  lat <- seq(42, 47, 1)
  exp <- list(data = t, lat = lat, lon = lon)
  o <- runif(29 * 29) * 3000
  dim(o) <- c(lat = 29, lon = 29)
  lon <- seq(3.125, 10.125, 0.25) - 100
  lat <- seq(41.125, 48.125, 0.25) - 60
  oro <- list(data = o, lat = lat, lon = lon)
  attr(oro, "class") <- "s2dv_cube"

  expect_error(
    res <- CST_RFTemp(exp, oro, xlim = c(1, 3), ylim = c(1, 3), time_dim = 'ftime'),
                      paste("Parameter 'data' must be of the class",
                            "'s2dv_cube', as output by CSTools::CST_Load."))
  attr(exp, "class") <- "s2dv_cube"

  expect_error(
    res <- CST_RFTemp(exp, oro, xlim = c(1, 3), ylim = c(1, 3), time_dim = 'ftime'),
    "Orography not available for selected area"
  )

  oro$lon <- oro$lon + 100
  oro$lat <- oro$lat + 60

  expect_error(
    res <- CST_RFTemp(exp, oro, xlim = c(3, 8), ylim = c(43, 46), time_dim = 'ftime'),
    "Downscaling area not contained in input data"
  )

  expect_warning(
    resl <- CST_RFTemp(exp, oro, lapse = 6.5),
    "Selected time dim: ftime"
  )

  dimexp <- dim(exp$data)
  expect_equal(dim(resl$data), c(lon = 16, lat = 16, dimexp["ftime"],
                                dimexp["sdate"], dimexp["dataset"],
                                dimexp["member"]))
  expect_warning(
  resd <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                      nolapse = TRUE), NA)
  dim(resd$data) <- c(16, 16, 4 * 3 * 2 * 2)
  resm <- apply(resd$data, c(1, 2), mean)
  expect_equal(mean(oro$data[7:22, 7:22]), mean(resm), tolerance = 1e-10)

  # Test precomputation of delta based with nolapse
  delta <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                      nolapse = TRUE, compute_delta = TRUE)
  resdnl <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                       nolapse = TRUE, delta = delta)
  expect_equal(mean(resdnl$data), mean(resd$data), tolerance = 1e-10)

  # Test precomputation of delta based with lapse rate
  delta <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                      lapse = 6.5, compute_delta = TRUE)
  resdl <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                      delta = delta)
  expect_equal(mean(resdl$data), mean(resl$data), tolerance = 1e-10)

  expect_warning(
  resd <- CST_RFTemp(exp, oro, time_dim = c("ftime", "sdate", "member"),
                      nolapse = TRUE, method = "nearest"), NA)
  dim(resd$data) <- c(16, 16, 4 * 3 * 2 * 2)
  resm <- apply(resd$data, c(1, 2), mean)
  expect_equal(mean(oro$data[7:22, 7:22]), mean(resm), tolerance = 1e-10)
})
