# tests/testthat/test-data_overview_module.R

# test validate number of rows ------------------------------------------------
test_that("Test sample rows", {
  testServer(data_overview_server, {

    session$userData$dt <- reactiveValues(
      dt = list('iris' = as.data.table(iris), 'mtcars' = as.data.table(mtcars)),
      act_name = 'iris'
    )

    session$userData$dt_names <- reactive({
      names(session$userData$dt$dt)
    })

    session$userData$dt$df_info <- reactive({
      req(session$userData$dt)

      lapply(session$userData$dt$dt, df_info)
    })

    session$setInputs(sel_dataset = 'iris', size_sample = 0)

    expect_error(idx())

  })
})

# test first rows -------------------------------------------------------------
test_that("Test first rows", {
  testServer(data_overview_server, {

    session$userData$dt <- reactiveValues(
      dt = list('iris' = as.data.table(iris), 'mtcars' = as.data.table(mtcars)),
      act_name = 'iris'
    )

    session$userData$dt_names <- reactive({
      names(session$userData$dt$dt)
    })

    session$userData$dt$df_info <- reactive({
      req(session$userData$dt)

      lapply(session$userData$dt$dt, df_info)
    })

    session$setInputs(size_sample = 5,
                      sel_dataset = 'iris',
                      radio_sample = 'first')

    expect_equal(data_filtered(), iris[1:5, ] |> as.data.table())

  })
})

# test last rows -------------------------------------------------------------
test_that("Test last rows", {
  testServer(data_overview_server, {

    session$userData$dt <- reactiveValues(
      dt = list('iris' = as.data.table(iris), 'mtcars' = as.data.table(mtcars)),
      act_name = 'iris'
    )

    session$userData$dt_names <- reactive({
      names(session$userData$dt$dt)
    })

    session$userData$dt$df_info <- reactive({
      req(session$userData$dt)

      lapply(session$userData$dt$dt, df_info)
    })

    session$setInputs(size_sample = 3,
                      sel_dataset = 'mtcars',
                      radio_sample = 'last')

    expect_equal(data_filtered(), mtcars[30:32, ], ignore_attr = TRUE)

  })
})

# test sample of rows ---------------------------------------------------------
test_that("Test sample rows", {
  testServer(data_overview_server, {

    session$userData$dt <- reactiveValues(
      dt = list('iris' = as.data.table(iris), 'mtcars' = as.data.table(mtcars)),
      act_name = 'iris'
    )

    session$userData$dt_names <- reactive({
      names(session$userData$dt$dt)
    })

    session$userData$dt$df_info <- reactive({
      req(session$userData$dt)

      lapply(session$userData$dt$dt, df_info)
    })

    session$setInputs(size_sample = 5,
                      sel_dataset = 'iris',
                      radio_sample = 'first')

    # test for equality (unlist to avoid error caused by row.names)
    expect_equal(data_filtered() |> unlist(), iris[idx(),] |> unlist())
  })
})
