# This unit test tests the case that using values() to define the depended
# and depending dimensions. The depending dimension should be a list with 
# names that are the values of depended dimensions.

context("Start() using values() to define dependency relations")


path <- '/esarchive/exp/CMIP6/dcppA-hindcast/hadgem3-gc31-mm/cmip6-dcppA-hindcast_i1p1/DCPP/MOHC/HadGEM3-GC31-MM/dcppA-hindcast/r1i1p1f2/Omon/tos/gn/v20200417/$var$_Omon_HadGEM3-GC31-MM_dcppA-hindcast_s$sdate$-r1i1p1f2_gn_$chunk$.nc'

sdates <- c('2016', '2017', '2018')
chunks <- array(dim = c(chunk = 3, sdate = 3))
chunks[ , 1] <- c("201701-201712", "201801-201812", "201901-201912")
chunks[ , 2] <- c("201801-201812", "201901-201912", "202001-202012")
chunks[ , 3] <- c("201901-201912", "202001-202012", "202101-202112")

test_that("1. ", {
suppressWarnings(
dat1 <- Start(dat = path,
             var = 'tos',
             sdate = sdates[1:2],
             chunk = list('2016' = chunks[, 1], '2017' = chunks[, 2]),
             chunk_depends = 'sdate',
             time = 'all',
             i = indices(450:460),
             j = indices(685:700),
             time_across = 'chunk',
             merge_across_dims = TRUE,
             return_vars = list(time = 'sdate'),
             retrieve = TRUE)
)

suppressWarnings(
dat2 <- Start(dat = path,
             var = 'tos',
             sdate = sdates,
             chunk = list('2016' = chunks[, 1], '2017' = chunks[, 2], '2018' = chunks[ ,3]),
             chunk_depends = 'sdate',
             time = 'all',
             i = indices(450:460),
             j = indices(685:700),
             time_across = 'chunk',
             merge_across_dims = TRUE,
             return_vars = list(time = 'sdate'),
             retrieve = TRUE)
)
suppressWarnings(
 dat3 <- Start(dat = path,
             var = 'tos',
             sdate = sdates,
             chunk = list(chunks[, 1], chunks[, 2], chunks[ ,3]),
             chunk_depends = 'sdate',
             time = 'all',
             i = indices(450:460),
             j = indices(685:700),
             time_across = 'chunk',
             merge_across_dims = TRUE,
             return_vars = list(time = 'sdate'),
             retrieve = TRUE)
)
  expect_equal(
  dat1[1,1,1:2,,,], 
  dat2[1,1,1:2,,,]
  )
  expect_equal(
  mean(dat2, na.rm = T),
  29.11137,
  tolerance = 0.0001
  )
  expect_equal(
  mean(dat1, na.rm = T),
  29.07394,
  tolerance = 0.0001
  )
  expect_equal(
  dat2[1, 1, 2, 2, 1:3, 10],
  c(28.38624, 28.19837, 28.08603),
  tolerance = 0.0001
  )
  expect_equal(
  as.vector(dat2),
  as.vector(dat3)
  )
})

