context("s2dv::Smoothing test")

##############################################
  # dat1
  set.seed(1)
  dat1 <- array(rnorm(720), c(dat = 1, sdate = 3, ftime = 120, lon = 2)) 

  # dat2
  set.seed(2)
  dat2 <- array(rnorm(363), c(member = 3, time = 121)) 

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

test_that("1. Input checks", {

  expect_error(
  Smoothing(c()),
  "Parameter 'data' cannot be NULL."
  )
  expect_error(
    Smoothing(c(NA, NA)),
    "Parameter 'data' must be a numeric array."
  )
  expect_error(
    Smoothing(array(1:10, dim = c(2, 5))),
    "Parameter 'data' must have dimension names."
  )
  expect_error(
    Smoothing(dat1, time_dim = 'a'),
    "Parameter 'time_dim' is not found in 'data' dimension."
  )
  expect_error(
    Smoothing(dat1, time_dim = 3),
    "Parameter 'time_dim' must be a character string."
  )
  expect_error(
    Smoothing(dat1, runmeanlen = 0),
    "Parameter 'runmeanlen' must be a positive integer."
  )
  expect_error(
    Smoothing(dat1, runmeanlen = 0.5),
    "Parameter 'runmeanlen' must be a positive integer."
  )
  expect_error(
    Smoothing(dat1, runmeanlen = 120),
    "Parameter 'runmeanlen' must be within [1, 119].",
    fixed = TRUE
  )
  expect_error(
    Smoothing(dat2, time_dim = 'time', runmeanlen = 122),
    "Parameter 'runmeanlen' must be within [1, 121].",
    fixed = TRUE
  )
  expect_error(
    Smoothing(dat1, ncore = 3.5),
    "Parameter 'ncores' must be a positive integer."
  )

})

##############################################
test_that("2. Output checks: dat1", {

  expect_equal(
    dim(Smoothing(dat1)),
    c(ftime = 120, dat = 1, sdate = 3, lon = 2)
  )
  expect_equal(
    mean(Smoothing(dat1), na.rm = TRUE),
    -0.01902183,
    tolerance = 0.0001
  )
  expect_equal(
    length(Smoothing(dat1)[which(is.na(Smoothing(dat1)))]),
    72
  )
  expect_equal(
    Smoothing(dat1)[1:7, 1, 2, 2],
    c(NA, NA, NA, NA, NA, NA, 0.01114821),
    tolerance = 0.0001
  )
  expect_equal(
    length(Smoothing(dat1, runmeanlen = 21)[which(is.na(Smoothing(dat1, runmeanlen = 21)))]),
    120
  )
  expect_equal(
    min(Smoothing(dat1, runmeanlen = 21), na.rm = TRUE),
    -0.6057508,
    tolerance = 0.0001
  )

})

##############################################
test_that("3. Output checks: dat2", {

  expect_equal(
    dim(Smoothing(dat2, time_dim = 'time')),
    c(time = 121, member = 3)
  )
  expect_equal(
    mean(Smoothing(dat2, time_dim = 'time'),  na.rm = TRUE),
    0.07041814,
    tolerance = 0.0001
  )
  expect_equal(
    length(Smoothing(dat2, time_dim = 'time')[which(is.na(Smoothing(dat2, time_dim = 'time')))]),
    36
  )
  expect_equal(
    min(Smoothing(dat2, time_dim = 'time', runmeanlen = 120), na.rm = TRUE),
    -0.0246432,
    tolerance = 0.0001
  )

})


