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

remove(list = ls())
gc()

# setting directory
work.dir <- "C:/Users/harta005/Projects/seed-germination-qtl/"
setwd(work.dir)

# load library
library(shiny)
library(topGO)
library(org.At.tair.db)
library(ggplot2)

# load variables for goe test
x <- org.At.tairCHR
all.genes <- as.list(as.character(read.csv('files/gene-list.csv', header = F)[, 1]))
hc.go.list <- as.data.frame(matrix(data = NA, nrow = 0, ncol = 8))
colnames(hc.go.list) <- c('GO.ID', 'Term', 'Annotated', 'Significant', 'Expected', 'Fisher', 
                          'FDR')


# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Gene ontology enrichment test for Joosen data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            textAreaInput(inputId = 'gene.list',
                          label = 'Put your list of gene here!',
                          width = '100%',
                          height = '400px',
                          value = '',
                          placeholder = "AT4G22890\nAT2G34630\nAT2G03270\nAT2G25590\nAT5G25130",
                          actionButton('button', label = 'Submit!')
                          ),
            selectInput(inputId = 'go.term', 
                        label = 'Select the GO term:', 
                        choices = c('biological process', 'molecular function', 'cellular component'), 
                        selected = 'biological process'
                        ),
            actionButton(inputId = 'submit', label = 'Submit')
        ),


        # Show a plot of the generated distribution
        mainPanel(
            downloadButton(outputId = 'download', 'Download'),
           DT::dataTableOutput("go.result")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    
    reactive.gene.list <- eventReactive(input$submit, {
        input$gene.list
    })
    
    # creating data table 
    data_table <- reactive({
        gene.list <- reactive.gene.list()
        gene.set <- unlist(strsplit(gene.list, '\n'))
        gene.set <- factor(as.integer(all.genes %in% gene.set))
        ontology <- ifelse(input$go.term == 'biological process', 'BP',
                           ifelse(input$go.term == 'molecular function', 'MF', 'CC'))
        
        names(gene.set) <- all.genes
        GOdata <- new("topGOdata",
                      description = "Analyzing clustering results", 
                      ontology = ontology,
                      allGenes = gene.set, 
                      annot = annFUN.org,mapping= "org.At.tair.db")
        resultFisher <- runTest(GOdata, algorithm = 'weight', statistic = "fisher")
        result.df <- GenTable(GOdata, pval = resultFisher,
                              orderBy = "Fisher", ranksOf = "Fisher", topNodes = length(resultFisher@score))
        result.df$FDR <- round(p.adjust(p = result.df$pval, method = 'fdr'), 4)
        result.df$pval <- round(as.numeric(result.df$pval), 4)
        result.df <- result.df[order(result.df$FDR), ]
        #result.df <- filter(result.df, FDR <= 0.001)
        #hc.go.list <- rbind(hc.go.list, result.df)
        result.df
    })
    
    output$go.result <- DT::renderDataTable({
        data_table()
    })
    
    output$download <- downloadHandler(
        filename = paste0(input$go.term, ".csv"),
        content = function(file) {
            write.csv(data_table(), file, row.names = FALSE)
        }
    )
}

# Run the application 
shinyApp(ui = ui, server = server)