# Chapter 7 - Three ways to export a table as CSV (try the CSV button of each table)
library(shiny)
library(bslib)
library(DT)
library(dplyr)
library(gapminder)   # 1,704 rows

shown <- select(gapminder, country, year, lifeExp)   # columns displayed in the tables

# A datatable with the "Buttons" extension (Copy + CSV)
dt_with_buttons <- function(data) {
  datatable(
    data,
    rownames = FALSE,
    extensions = "Buttons",
    options = list(
      dom = "Bfrtip",                      # B = Buttons, f = filter, r, t = table, i = info, p = pages
      buttons = list("copy", list(extend = "csv", filename = "gapminder")),
      pageLength = 8
    )
  )
}

ui <- page_fillable(
  title = "Exporting a table as CSV",
  layout_columns(
    col_widths = c(4, 4, 4),
    card(
      card_header("1. downloadButton() + downloadHandler()"),
      p("The file is written by R: it contains the", strong("whole data"), "(1,704 rows), whatever the table displays."),
      downloadButton("download_csv", "Download data (CSV)"),
      DTOutput("table_handler")
    ),
    card(
      card_header("2. DT Buttons, renderDT(server = FALSE)"),
      p("All the rows are sent to the browser: the CSV button exports", strong("1,704 rows.")),
      DTOutput("table_client")
    ),
    card(
      card_header("3. DT Buttons, renderDT() (default: server = TRUE)"),
      p("Only the current page is in the browser: the CSV button exports", strong("8 rows only!")),
      DTOutput("table_server")
    )
  )
)

server <- function(input, output, session) {
  # 1. Export done by R
  output$table_handler <- renderDT(datatable(shown, rownames = FALSE, options = list(dom = "tip", pageLength = 8)))
  output$download_csv <- downloadHandler(
    filename = \() "gapminder.csv",
    content  = \(file) readr::write_csv(gapminder, file)
  )

  # 2. Export done by the browser, with all the rows
  output$table_client <- renderDT(dt_with_buttons(shown), server = FALSE)

  # 3. Export done by the browser, with the current page only (the trap)
  output$table_server <- renderDT(dt_with_buttons(shown))
}

shinyApp(ui, server)
