# Chapter 9 - A gallery of inputs: each card shows a widget and the value R receives
library(shiny)
library(bslib)

# One card = the name of the function, the widget, and str(input$<id>)
input_card <- function(fun_name, widget, id) {
  card(
    card_header(code(fun_name)),
    widget,
    card_footer(verbatimTextOutput(paste0("value_", id)))
  )
}

ui <- page_fillable(
  title = "Shiny inputs",
  tags$style("pre { white-space: pre-wrap; }"),   # wrap long values
  layout_column_wrap(
    width = 1 / 3, heights_equal = "row",
    input_card("sliderInput()",
               sliderInput("price", "Price range (£)", min = 0, max = 100, value = c(20, 60)),
               "price"),
    input_card("selectInput(multiple = TRUE)",
               selectInput("country", "Countries",
                           choices = c("France", "Germany", "Spain", "United Kingdom"),
                           selected = c("France", "Spain"), multiple = TRUE),
               "country"),
    input_card("checkboxGroupInput()",
               checkboxGroupInput("market", "Markets",
                                  choices = c("Retail", "Wholesale", "Online"),
                                  selected = "Online", inline = TRUE),
               "market"),
    input_card("radioButtons()",
               radioButtons("unit", "Show revenue by",
                            choices = c("Day" = "day", "Week" = "week", "Month" = "month"),
                            selected = "week", inline = TRUE),
               "unit"),
    input_card("dateRangeInput()",
               dateRangeInput("dates", "Period", start = "2011-01-01", end = "2011-06-30"),
               "dates"),
    input_card("input_switch()",
               input_switch("cancel", "Include cancellations", value = TRUE),
               "cancel"),
    input_card("numericInput()",
               numericInput("top_n", "Number of products", value = 10, min = 1, max = 50),
               "top_n"),
    input_card("textInput()",
               textInput("search", "Product name contains", placeholder = "e.g. CHRISTMAS"),
               "search"),
    input_card("actionButton()",
               actionButton("go", "Update", icon = icon("rotate")),
               "go")
  )
)

server <- function(input, output, session) {
  ids <- c("price", "country", "market", "unit", "dates", "cancel", "top_n", "search")
  for (id in ids) {
    local({
      my_id <- id
      output[[paste0("value_", my_id)]] <- renderPrint(str(input[[my_id]]))
    })
  }
  # an action button is a counter: show it as a plain integer
  output$value_go <- renderPrint(str(as.integer(input$go)))
}

shinyApp(ui, server)
