library(shiny)
library(readxl)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.1     ✔ purrr   1.0.1
## ✔ tibble  3.1.8     ✔ dplyr   1.1.0
## ✔ tidyr   1.3.0     ✔ stringr 1.5.0
## ✔ readr   2.1.4     ✔ forcats 1.0.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(ggplot2)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(ggstar)

ui <- fluidPage(
  titlePanel("Data Exploration"),
  
  tabsetPanel(
    tabPanel("File upload",
             sidebarLayout(
               sidebarPanel("",
                  fileInput("upload", "Dataset", accept = ".csv"),
                  numericInput("n", "Preview rows", value = 5, min = 1, step = 1),
                  fileInput("error", "Uncertainty", accept = ".csv"),
                  ),
             mainPanel(
               tableOutput("head"),
               tableOutput("error")
             )
            )
            ),
    tabPanel("Concentrations",
             sidebarLayout(
               sidebarPanel("",
                            selectInput("xSelect",label="Select x-axis",choices=NULL),
                            selectInput("ySelect",label="Select y-axis",choices=NULL),
                            selectInput("fill",label="Select column to color points by",choices=NULL)
                            ),
               mainPanel("",
                         plotlyOutput("plot1",width = 800, height = 600)
                         )
             )
             ),
    tabPanel("One Ratio",
             sidebarLayout(
               sidebarPanel("",
                            selectInput("xSelect2",label="Select x-axis",choices=NULL),
                            selectInput("yNum",label="Select y-axis ratio numerator",choices=NULL),
                            selectInput("yDenom",label="Select y-axis ratio denominator",choices=NULL),
                            selectInput("fill2",label="Select column to color points by",choices=NULL)
               ),
               mainPanel("",
                         plotlyOutput("plot2",width = 800, height = 600)
               )
             )
    ),
    tabPanel("Ratio-Ratio",
             sidebarLayout(
               sidebarPanel("",
                            selectInput("xNum",label="Select x-axis ratio numerator",choices=NULL),
                            selectInput("xDenom",label="Select x-axis ratio denominator",choices=NULL),
                            selectInput("yNum2",label="Select y-axis ratio numerator",choices=NULL),
                            selectInput("yDenom2",label="Select y-axis ratio denominator",choices=NULL),
                            selectInput("fill3",label="Select column to color points by",choices=NULL)
               ),
               mainPanel("",
                         plotlyOutput("plot3",width = 800, height = 600)
               )
             )
    )
  )
  
)

server <- function(input, output, session) {
  data <- reactive({
    req(input$upload)
    
    ext <- tools::file_ext(input$upload$name)
    switch(ext,
           csv = vroom::vroom(input$upload$datapath, delim = ","),
           validate("Invalid file; Please upload a .csv file")
    )
  })
  
  uncertainty <- reactive({
    req(input$error)
    
    ext <- tools::file_ext(input$error$name)
    switch(ext,
           csv = vroom::vroom(input$error$datapath, delim = ","),
           validate("Invalid file; Please upload a .csv file")
    )
  })
  
  output$head <- renderTable({
    head(data(), input$n)
  })
  
  output$error <- renderTable({
    head(uncertainty())
  })

  observe({
    updateSelectInput(session,"xSelect",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"ySelect",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"fill",choices=colnames(data()))
  })
  
  output$plot1 <- renderPlotly({

    ggplotly(ggplot() +
               geom_errorbar(aes(x = data()[[paste(input$xSelect)]],
                                 ymin = data()[[paste(input$ySelect)]] - uncertainty()[[paste(input$ySelect)]],
                                 ymax = data()[[paste(input$ySelect)]] + uncertainty()[[paste(input$ySelect)]])) +
               geom_errorbar(aes(y = data()[[paste(input$ySelect)]],
                                 xmin = data()[[paste(input$xSelect)]] - uncertainty()[[paste(input$xSelect)]],
                                 xmax = data()[[paste(input$xSelect)]] + uncertainty()[[paste(input$xSelect)]])) +
               geom_point(aes(x = data()[[paste(input$xSelect)]],
                                         y = data()[[paste(input$ySelect)]],
                              fill = data()[[paste(input$fill)]]),
                          shape = 21,
                          size = 3) +
      theme_bw() +
      labs(x = input$xSelect, y = input$ySelect))
  })
  
  observe({
    updateSelectInput(session,"xSelect2",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"yNum",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"yDenom",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"fill2",choices=colnames(data()))
  })
  
  output$plot2 <- renderPlotly({
    
    y1 <- data()[[paste(input$yNum)]]
    y2 <- data()[[paste(input$yDenom)]]
    y1Sig <- uncertainty()[[paste(input$yNum)]]
    y2Sig <- uncertainty()[[paste(input$yDenom)]]
    
    ggplotly(ggplot() +
               geom_errorbar(aes(x = data()[[paste(input$xSelect2)]],
                                 ymin = (y1/y2) - ((y1/y2)*sqrt(((y1Sig/y1)^2) + ((y2Sig/y2)^2))),
                                 ymax = (y1/y2) + ((y1/y2)*sqrt(((y1Sig/y1)^2) + ((y2Sig/y2)^2))))) + 
               geom_errorbar(aes(y = data()[[paste(input$yNum)]]/data()[[paste(input$yDenom)]],
                                 xmin = data()[[paste(input$xSelect2)]] - uncertainty()[[paste(input$xSelect2)]],
                                 xmax = data()[[paste(input$xSelect2)]] + uncertainty()[[paste(input$xSelect2)]])) +
               geom_point(aes(x = data()[[paste(input$xSelect2)]],
                              y = data()[[paste(input$yNum)]]/data()[[paste(input$yDenom)]],
                              fill = data()[[paste(input$fill2)]]),
                          shape = 21,
                          size = 3) +
               theme_bw() +
      labs(x = input$xSelect2, 
           y = paste0(input$yNum,"/",input$yDenom)))
  })
  
  observe({
    updateSelectInput(session,"xNum",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"xDenom",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"yNum2",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"yDenom2",choices=colnames(data()))
  })
  
  observe({
    updateSelectInput(session,"fill3",choices=colnames(data()))
  })
  
  output$plot3 <- renderPlotly({
    
    y1 <- data()[[paste(input$yNum2)]]
    y2 <- data()[[paste(input$yDenom2)]]
    y1Sig <- uncertainty()[[paste(input$yNum2)]]
    y2Sig <- uncertainty()[[paste(input$yDenom2)]]
    
    x1 <- data()[[paste(input$xNum)]]
    x2 <- data()[[paste(input$xDenom)]]
    x1Sig <- uncertainty()[[paste(input$xNum)]]
    x2Sig <- uncertainty()[[paste(input$xDenom)]]
    
    ggplotly(ggplot() +
               geom_errorbar(aes(x = data()[[paste(input$xNum)]]/data()[[paste(input$xDenom)]],
                                 ymin = (y1/y2) - ((y1/y2)*sqrt(((y1Sig/y1)^2) + ((y2Sig/y2)^2))),
                                 ymax = (y1/y2) + ((y1/y2)*sqrt(((y1Sig/y1)^2) + ((y2Sig/y2)^2))))) + 
               geom_errorbar(aes(y = data()[[paste(input$yNum2)]]/data()[[paste(input$yDenom2)]],
                                 xmin = (x1/x2) - ((x1/x2)*sqrt(((x1Sig/x1)^2) + ((x2Sig/x2)^2))),
                                 xmax = (x1/x2) + ((x1/x2)*sqrt(((x1Sig/x1)^2) + ((x2Sig/x2)^2))))) + 
               geom_point(aes(x = data()[[paste(input$xNum)]]/data()[[paste(input$xDenom)]],
                              y = data()[[paste(input$yNum2)]]/data()[[paste(input$yDenom2)]],
                              fill = data()[[paste(input$fill3)]]),
                          shape = 21,
                          size = 3) +
               theme_bw() +
               labs(x = paste0(input$xNum,"/",input$xDenom), 
                    y = paste0(input$yNum2,"/",input$yDenom2)))
  })
}

shinyApp(ui = ui, server = server)
## 
## Listening on http://127.0.0.1:7245