context("s2dv::WeightedCells tests")

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

# dat1
set.seed(1)
data1 <- array(rnorm(5), dim = c(lat = 5))
set.seed(2)
lat1 <- array(rnorm(5)*5)

# dat2
set.seed(1)
data2 <- array(rnorm(60), dim = c(sdate = 10, lat = 2, lon = 3))
set.seed(2)
lat2 <- array(rnorm(2)*10)


##############################################
test_that("1. Input checks", {
  # data
  expect_error(
    WeightedCells(c()),
    "Parameter 'data' cannot be NULL."
  )
  expect_error(
    WeightedCells('lat'),
    "Parameter 'data' must be a numeric array."
  )
  expect_error(
    WeightedCells(rnorm(5)),
    "Parameter 'data' must be at least latitude dimension."
  )
  expect_error(
    WeightedCells(array(rnorm(5), dim = c(5))),
    "Parameter 'data' must have dimension names."
  )
  #lat_dim
  expect_error(
    WeightedCells(data1, lat1, 3),
    "Parameter 'lat_dim' must be a character string."
  )
  expect_error(
    WeightedCells(data1, lat1, 'latitude'),
    "Parameter 'lat_dim' is not found in 'data'."
  )
  #lat
  expect_error(
    WeightedCells(data1, NULL),
    "Parameter 'lat' cannot be NULL."
  )
  expect_error(
    WeightedCells(data1, list(lat1)),
    "Parameter 'lat' must be a numeric vector or array."
  )
  expect_error(
    WeightedCells(data1, rnorm(10)),
    "Length of parameter 'lat' doesn't match the length of latitudinal dimension in parameter 'data'."
  )
  # method
  expect_error(
    WeightedCells(data1, lat1, method = 1.5),
    "Parameter 'method' must be one of 'cos' or 'sqrtcos'."
  )
  # ncores
  expect_error(
    WeightedCells(data1, lat1, ncores = 1.5),
    "Parameter 'ncores' must be either NULL or a positive integer."
  )

})

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

  expect_equal(
    dim(WeightedCells(data1, lat1)),
    c(lat = 5)
  )
  expect_equal(
    as.vector(WeightedCells(data1, lat1)),
    c(-0.6245359, 0.1836194, -0.8276192, 1.5875256, 0.3294997),
    tolerance = 0.0001
  )

})

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

  expect_equal(
    dim(WeightedCells(data2, lat2)),
    c(sdate = 10, lat = 2, lon = 3)
  )
  expect_equal(
    as.vector(WeightedCells(data2, lat2))[1:5],
    c(-0.6187938, 0.1813978, -0.8254109, 1.5757744, 0.3254787),
    tolerance = 0.0001
  )
  expect_equal(
    dim(WeightedCells(data2, lat2)),
    dim(data2)
  )
  expect_equal(
    WeightedCells(data2, lat2),
    WeightedCells(data2, lat2, method = 'sqrtcos')*as.vector(sqrt(cos(lat2*pi/180))),
    tolerance = 0.01
  )

})

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