# load needed libraries
library(shiny)
library(bslib)
library(bsicons)
library(later)

# user interface
ui <- page_sidebar(
    theme = bs_theme(preset = "cosmo"),
    title = "Shiny Demo App",
    sidebar = sidebar(
        title = h2(bs_icon("gear"), "Settings"),
        bg = "peachpuff",
        sliderInput(
            "slider1",
            label = "Select a value",
            min = 1,
            max = 1000,
            value = 200
        ),
        textInput(
            "graphTitle",
            label = "Enter a graph name:",
            value = "My Example Graph"
        ),
        checkboxInput(
            "showColor",
            label = "Show color?"
        ),
        selectInput(
            "colorChoice",
            label = "Choose a color:",
            choices = list("Red" = "red", "Blue" = "blue", "Green" = "green", "Peachpuff" = "peachpuff"),
            selected = "red"
        ),
        radioButtons(
            "graphType",
            label = "Graph type:",
            choices = list("Normal Data" = "normal", "Uniform Data" = "uniform"),
            selected = "normal"
        ),
        actionButton(
            "button1",
            "Generate new data!",
            icon = icon("database")
        ),
        textOutput("someText")
    ),
    card(
        card_header("Overview"),
        card_body(
            p("This app shows some of the features of the Shiny framework.", style="color: #ff0000"),
            p("By the way, check out this website: ", a(href="https://www.beauchrist.com", "An awesome website"))
        )
    ),
    card(
        plotOutput("graph1")
    )
)

# back-end server code
server <- function(input, output) {
    showingText <- reactiveVal(FALSE)
    
    output$someText <- renderText({
        if(showingText() == TRUE) {
            return(paste("New data generated!"))
        } else {
            return(paste(""))
        }
    })
    
    normalData <- reactive({
        input$button1
        rnorm(input$slider1)
    })
    
    unifData <- reactive({
        input$button1
        runif(input$slider1)
    })
    
    output$graph1 <- renderPlot({
        if(input$graphType == "normal") {
            if(input$showColor == TRUE) {
                hist(normalData(), main=input$graphTitle, col=input$colorChoice)
            } else {
                hist(normalData(), main=input$graphTitle)
            }
        } else {
            if(input$showColor == TRUE) {
                hist(unifData(), main=input$graphTitle, col=input$colorChoice)
            } else {
                hist(unifData(), main=input$graphTitle)
            }
        }
    })
    
    observeEvent(input$button1, {
        showingText(TRUE)
        later(function() {
            showingText(FALSE)
        }, delay = 1)
    })
}

# run!
shinyApp(ui = ui, server = server)
