# setup tinytest for checkmate functionality
library("tinytest")
library("checkmate")
using("checkmate")

# ------ get_person ------

persons <- authors[["person"]]

# returns a person object
p <- get_person("jfisher", persons = persons)
expect_true(inherits(p, "person"))

# returns the correct number of entries
expect_equal(length(p), 1L)

# multiple ids returned in requested order
ids <- c("jfisher", "rbartholomay")
p2 <- get_person(ids, persons = persons)
expect_equal(length(p2), 2L)
expect_equal(names(p2), ids)

# order is preserved when reversed
p3 <- get_person(rev(ids), persons = persons)
expect_equal(names(p3), rev(ids))

# missing id raises an error
expect_error(get_person("zzznobody", persons = persons))

# duplicate ids raise an error
expect_error(get_person(c("jfisher", "jfisher"), persons = persons))

# NA raises an error
expect_error(get_person(NA_character_, persons = persons))

# ------ filter_data_list ------

if (requireNamespace("htmltools", quietly = TRUE)) {
  f <- filter_data_list("my-table")

  # returns a function
  expect_true(is.function(f))

  # calling the function produces an htmltools tagList
  result <- f(c("b", "a", "c"), "type")
  expect_true(inherits(result, "shiny.tag.list"))

  # datalist id is constructed from table_id and column name
  html <- as.character(htmltools::tagList(result))
  expect_true(grepl("my-table-type-list", html))

  # options are sorted (values appear as attributes)
  a_pos <- regexpr('value="a"', html, fixed = TRUE)
  b_pos <- regexpr('value="b"', html, fixed = TRUE)
  expect_true(a_pos < b_pos)

  # aria-label is set
  expect_true(grepl('aria-label="Filter type"', html))

  # custom style is applied
  f_styled <- filter_data_list("t", style = "color:red;")
  result_styled <- f_styled("x", "col")
  html_styled <- as.character(htmltools::tagList(result_styled))
  expect_true(grepl("color:red;", html_styled))

  # invalid table_id raises an error
  expect_error(filter_data_list(""))
  expect_error(filter_data_list(123))
}
