#
# This is the server logic of a Shiny web application. You can run the
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

#Installs the required packages if they are not already installed and loads them

required_packages <- list("shiny","readxl", "pROC", "MASS", "tidyverse","finalfit","ggplot2","patchwork")

for (package in required_packages){
  
  print(package)
  if(!require(package, character.only = TRUE)) install.packages(package)
  library(package, character.only = TRUE)

  
}
 
# Define server logic required to draw a histogram
shinyServer(function(input, output) {


  
  # output$data <- renderTable({
  #   
  #   req(input$upload)
  #   
  #   df <- read_excel(input$upload$datapath)
  #   df$Sex <- as.factor(df$Sex)
  #   df$ICU <- as.factor(df$ICU)
  #   df$Outcome <- as.factor(df$Outcome)
  #     
  #   # Removing columns that are all NAs
  #   df <- df[,colSums(is.na(df))<nrow(df)]
  #   
  #   OnlyExams <- c(colnames(df)[7:ncol(df)])
  #   Predictors <- c("Age","Sex","ICU",OnlyExams)
  #   
  #   df %>% 
  #     distinct(Patient_ID, .keep_all = TRUE) %>% 
  #     summary_factorlist("Outcome", OnlyExams, 
  #                        total_col = TRUE, add_col_totals = TRUE, p = TRUE, cont = "median",
  #                        add_row_totals = TRUE, include_row_missing_col = TRUE) -> stats_exams
  #   print(stats_exams)
  #   
  #   })
  
    output$ROC <- renderPlot({
      req(input$upload)
      
      df <- read_excel(input$upload$datapath)
      
      df$Outcome <- as.factor(df$Outcome)
      
      df <- df[,colSums(is.na(df))<nrow(df)]
      
      OnlyExams <- c(colnames(df)[3:ncol(df)])
      
      plotList <- list()
      
      i <- 0
      
      for (exam in c(OnlyExams)) {
        
        i <- i + 1
        rocobj <- pROC::roc(df$Outcome, unlist(df[,exam]), levels=c("Alive","Deceased"), direction="<")
        auc <- round(auc(rocobj),4)
        
        plotList[[i]] <- ggroc(rocobj, colour = 'steelblue', size = 2) +
          ggtitle(paste0('ROC Curve ' ,exam, ' (AUC = ', auc, ')')) +
          theme_minimal()  + 
          geom_segment(aes(x = 1, xend = 0, y = 0, yend = 1),
                       color="darkgrey", linetype="dashed")+
          theme(
            
            plot.title = element_text(size = 15),
            axis.title = element_text(size = 13),
            axis.text = element_text(size = 13)
            
          )
        
        plot(plotList[[i]])
      }
      
      wrap_plots(plotList, heights = 10, widths = 10 )
      
    })
  
  
  
  output$input_table <- downloadHandler(
    filename = "Standard_input_table_shareable_download.xlsx",
    content = function(file){

      file.copy("www/Standard_input_table_shareable.xlsx", file)
    }
  )
  
  
})
