#
# Downloading Data
# https://shiny.rstudio.com/gallery/file-download.html
#
# Q: Shiny app: downloadHandler does not produce a file
# A: Note the download button does not work in the RStudio viewer. 
# Your friend might be using the RStudio viewer to view the app. 
# If that is the case, please open the app in the external web browser 
# (there is a drop-down list on the right of the "Run App" button: 
# Run in Window, Run in Viewer Pane, Run External; choose the last one).
#



# UI ----------------------------------------------------------------------

ui <- navbarPage("",
fluidPage(
  titlePanel('Downloading Data'),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose a dataset:", 
                  choices = c("rock", "pressure", "cars")),
      downloadButton('downloadData', 'Download')
    ),
    mainPanel(
      tableOutput('table')
    )
  )
)
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  
    datasetInput <- reactive({
      switch(input$dataset,
             "rock" = rock,
             "pressure" = pressure,
             "cars" = cars)
    })
    
    output$table <- renderTable({
      datasetInput()
    })
    
    output$downloadData <- downloadHandler(
      filename = function() { 
        paste(input$dataset, '.csv', sep='') 
      },
      content = function(file) {
        write.csv(datasetInput(), file)
      }
    )
  }  


shinyApp(ui = ui, server = server)

