# This is the user-interface definition of a Shiny web application.
# You can find out more about building applications with Shiny here:
#  
# http://shiny.rstudio.com
#
# header = dashboardHeaderPlus(title = 'CoCoCoNet',titleWidth=150)
.libPaths("/usr/local/lib/R/site-library")

library(shiny,quietly=T)
library(shinyWidgets,quietly=T)
library(shinydashboard,quietly=T)
library(shinydashboardPlus,quietly=T)
library(shinyBS,quietly=T)  # bootstrap
library(shinyalert,quietly=T)


# Source the downloads table 
source("summary_table.R")


header = dashboardHeader(
    title = div('CoCoBLAST'),
    titleWidth=150)


sidebar = dashboardSidebar(
    width = 150,
    sidebarMenu(
        id = 'tabs',
        menuItem("Home",tabName =  "home", icon = icon("home")),
        # menuItem("Comparison", tabName = "coexnet", icon = icon("project-diagram")), 

        menuItem('Expression',tabName = 'coexp',icon = icon('magnifying-glass-chart')),
        menuItem('Connectivity',tabName = 'enrich',icon = icon('sitemap')),
        menuItem('Conservation',tabName = 'cons',icon = icon('diagram-project')),
       
        
        menuItem("Data download",tabName = 'download_data',icon = icon("download"))
        # menuItem("Help",icon = icon("question"),href = "https://github.com/johnlee4/CoCoCoNet")
    )
)

# href='https://cocoblast.ccbr.utoronto.ca/files/'

##################################################################################################*
######################################### Start Main body #########################################
##################################################################################################*

body = dashboardBody(   
    tabItems(
        tabItem( # home page
            tabName = 'home',
            fluidPage(
                fluidRow(
                    box(status='primary',
                        width = NULL,
                        solidHeader=F,
                        collapsible = FALSE, 
				 		collapsed=FALSE,                

                        p(h2("Welcome to CoCoBLAST!"),
                          HTML("How can we study gene function across phylogenetically diverse species? One way is to compare gene coexpression signatures across species because genes that share a function are expressed in similar contexts. We collected 362,772 samples from 7,767 datasets, and built high-quality, meta-analytic gene coexpression networks for 142 species. (details on coexpression network construction available at CoCoCoNet
                                    <sup><a href='https://academic.oup.com/nar/article/48/W1/W566/5835815' target='_blank'> 1</a></sup>). We obtained orthology predictions for 142 species from eggNOG DB
                                    <sup><a href='https://academic.oup.com/nar/article/51/D1/D389/6833261' target='_blank'> 2</a> </sup>. This large collection of data permits the evaluation of coexpression relationships across the tree of life: from fungi to animals to plants."),
                          br(),br(),

                          h4('Our coexpression connectivity and conservation metrics'),
                          HTML("We use EGAD <sup><a href='https://academic.oup.com/bioinformatics/article/33/4/612/2664343' target='_blank'> 3</a></sup> to check if the  genes of interest form a cohesive module in a coexpression network. The neighbor voting method predicts whether a gene belongs to a set by counting how many of its network neighbors already belong, then ranks genes by this count to measure predictive performance. A high AUROC indicates that genes with a similar connectivity also share a known annotation (i.e., belonging to the same gene set, or functional category)."),
                          br(),
                          
                          HTML("The coexpression conservation score <sup><a href='https://academic.oup.com/nar/article/50/8/4302/6572361?login=false' target='_blank'> 4</a> </sup> measures how well a gene’s coexpression partners in one species are preserved in another, calculated as the average AUROC of neighbor rankings in both directions."),
                          br(),br(),
                              
                          HTML('With <b>CoCoBLAST</b>,  you can input a gene (or a set of genes) of interest within a reference species and perform the following analysis:  <ol>
                            <li>explore the expression of orthologs across 142 species,</li>
                            <li>evaluate the connectivity of genes in the reference coexpression network, and</li>
                            <li>search for genes with conserved coexpression partners in a target species</li>
                           </ol>')
                          ),
                         
                        div(img(src="cocoblast_summary_views.png",height='95%',width='95%'), align='center'),
                        br(),
                        HTML("Feel free to contact Hamsini Suresh at <b>hamsinisuresh6@gmail.com</b> (or) Leon French at <b>leon.french@utoronto.ca</b> to report an issue, suggest an update, or ask for help.")
                        ) # end of box
                    )
                )                                    
        ),  #end of home page

        tabItem(
            tabName = "coexp",
            fluidPage(   
                titlePanel('Gene Expression'),
                HTML("To query the expression of a gene in multiple species, input a gene from a reference species, then hit “Submit”. CoCoBLAST will output the TPM-normalized expression of the gene (and its orthologs in other species), and visualize the log2-scaled expression values across the species phylogeny using a circular heatmap."),
                br(),  br(),        
                
                fluidRow(
                    box(
                        title='Enter gene',status='primary',width = NULL,
                        solidHeader=T,

                        #input box (typing)
                        # begin paste gene list
                        fluidRow(
                            # column( width=3),
                            
                            column( width=3.,
                                textInput(  "coexp_input", 
                                    label ="Look for the following genes...",value = "RPL12"
                                    
                                ),                          
                                bsTooltip(                      
                                    id="coexp_input", options = list(container = "body"),placement='right',
                                    title= "Enter gene (gene name or Ensembl ID)"
                                ),                                  
                                selectInput(                    # select species
                                    inputId="coexp_specA",selected='human',selectize=F,
                                    label='In this species...',
                                    choices=speciesList2
                                ),

                                actionBttn(
                                    'coexp_submit','Submit',icon=icon('search') 
                                )    ,

                                bsTooltip(id='coexp_submit',placement = 'right',options = list(container = "body"),
                                    title = "Warning: Only click submit once: A delay may occur if our servers are busy."
                                )                                                   
                                
                            )

                        ) # end of coexp fluid row
                    ),
                    box(title = 'Gene expression', status = 'primary', width=NULL, solidHeader=T, collapsible = TRUE,collapsed=FALSE, 
                        fluidRow( 
                            column(
                            width = 6,
                            HTML("Explore the expression of gene (or homologs) across species (TPM-normalized)"),
                            DT::dataTableOutput("exp_table")                          
                        ),
                            column(
                            width = 6,
                            HTML("Plot heatmap of expression across species (log2(TPM + 1))"),
                            plotOutput(outputId ="exp_tree", height = 400)                         
                        ) 
                      )
                   )

                )
            )),  # end of tab item (coexp)
                
        tabItem(
            tabName = "cons",
            fluidPage(   
                titlePanel('Coexpression conservation'),
                HTML("To query coexpression conservation scores, input a gene from a reference species, select a target species, then hit “Submit”. CoCoBLAST will then do several tasks:"),
                tags$ol(
                    tags$li('It will find the 50 top coexpressed genes in the target species, showing each gene pair’s rank, as well as the reciprocal rank.'),
                    tags$li('Next, it looks for paralogs for each input gene in the reference species, maps these via orthology to the target species, and plots a heatmap and network of coexpression conservation scores.')
                ),br(),

                
                # "),
                # maps these genes to the target species and a heatmap of scores, and a network between orthologs. 


                fluidRow(
                    box(
                        title='Coexpression Conservation',status='primary',width = NULL,
                        solidHeader=T,

                        #input box (typing)
                        # begin paste gene list
                        fluidRow(
                            # column( width=3),
                            
                            column( width=3.,
                                textInput(  "cons_input", 
                                    label ="Look for the following genes...",value = "Tubb4b"
                                    
                                ),                          
                                bsTooltip(                      
                                    id="cons_input", options = list(container = "body"),placement='right',
                                    title= "Mutiple genes can be queried simultaneously with mutiple genes separated by a comma."
                                ),                                  
                                selectInput(                    # select species
                                    inputId="cons_specA",selected='mouse',selectize=F,
                                    label='In this species...',
                                    choices=speciesList
                                ),
                                                            selectInput(                    # select species
                                    inputId="cons_specB",selected='human',selectize=F,
                                    label='Then compare them to orthologs in... ',
                                    choices=speciesList
                                ),

                                actionBttn(
                                    'cons_submit','Submit',icon=icon('search') 
                                )    ,

                                bsTooltip(id='cons_submit',placement = 'right',options = list(container = "body"),
                                    title = "Warning: Only click submit once: A delay may occur if our servers are busy."
                                )

                                # bsTooltip(                      
                                #     id='cons_submit', options = list(container = "body"),placement='right',
                                #     title= "Mutiple genes can be queried simultaneously. Mutple genes should be separated by a comma."
                                # ),                                  
                                
                            )

                        )
                    ),
                    box(title = 'Tables', status = 'primary', width=NULL, solidHeader=T, collapsible = TRUE,collapsed=FALSE, 
                        fluidRow( 
                            column(width = 1,
                                htmlOutput('viewText11') # view
                            ),
                            column(width = 2,
                                uiOutput('tableSelector')
                            ),
                            column(width = 1,
                                htmlOutput('viewText22')     # for...
                            ),
                            column(width = 2,
                                uiOutput('geneSelector1')      
                            ),
                            column(width=1,
                                # htmlOutput('viewText3')     #  paralogs and orthologs
                            ),
                            column(width=2, 
                                # uiOutput('tnseSpecSelector')
                            ), 
                            column(width=3,
                                # uiOutput('bipart_slider')
                            )
                        ),br(),
                        fluidRow(
                            column(width = 8,
                                DT::dataTableOutput('cons_table')
                            ),
                            column(width=4,
                                uiOutput('downloadflag'),
                                uiOutput('option'),
                                uiOutput('connectionNumber'),
                                uiOutput('downloadButton')  
                            )
                        )
                    ),
                    box(title = 'Figures', status = 'primary', width=NULL, solidHeader=T, collapsible = TRUE,collapsed=FALSE,
                        fluidRow( 
                            column(width = 1,
                                htmlOutput('viewText1') # view
                            ),
                            column(width = 2,
                                uiOutput('figSelector')
                            ),
                            column(width = 1,
                                htmlOutput('viewText2')     # for...
                            ),
                            column(width = 2,
                                uiOutput('geneSelector')      
                            ),
                            column(width=2,
                                htmlOutput('viewText3')     #  paralogs and orthologs
                            ),
                            column(width=2, 
                                uiOutput('tnseSpecSelector')
                            ), 
                            column(width=2,
                                uiOutput('bipart_slider')
                            )
                            
                        ),
                        fluidRow(
                            column(width = 8,
                                plotOutput('mainFig',height='600px') # ,click = 'click_pt'
                            ),

                            column(width=4,
                                uiOutput('scoreThres'),
                                visNetworkOutput('bipartite',height='600px')
                            )
                        )                    
                    )

                )
            ) # end fluid page
        ),  # end tab item (cons)

        tabItem(
            tabName = "enrich",
            fluidPage(   
                titlePanel('Gene set connectivity'),
                HTML("To query the modularity of a set of genes, enter a comma-separated list of gene names or IDs from one of the 142 species, and hit “Submit”. CoCoBLAST will then summarize the following:"),
                tags$ol(
                    tags$li('Coexpression of genes within the species-specific coexpression network.'),
                    tags$li('Connectivity of genes within the network. Since genes with shared functions are preferentially connected, CoCoBLAST uses the EGAD R package to assess the strength of coexpression of input genes relative to random gene sets of equal length.')
                ),
                
                br(),
                
                fluidRow(
                    box(
                        title='Enter list of genes',status='primary',width = NULL,
                        solidHeader=T,

                        #input box (typing)
                        # begin paste gene list
                        fluidRow(
                            # column( width=3),
                            
                            column( width=3.,
                                textInput(  "egad_input", 
                                    label ="Look for the following genes...",value = "MEF2C,CDH5,GJA5,PECAM1,DCN"
                                    
                                ),                          
                                bsTooltip(                      
                                    id="egad_input", options = list(container = "body"),placement='right',
                                    title= "Enter a list of genes separated by a comma."
                                ),                                  
                                selectInput(                    # select species
                                    inputId="egad_specA",selected='human',selectize=F,
                                    label='In this species...',
                                    choices=speciesList2
                                ),

                                actionBttn(
                                    'egad_submit','Submit',icon=icon('search') 
                                )    ,

                                bsTooltip(id='egad_submit',placement = 'right',options = list(container = "body"),
                                    title = "Warning: Only click submit once: A delay may occur if our servers are busy."
                                )                                                   
                                
                            )

                        ) # end of EGAD fluid row
                    ),
                    box(title = 'Gene set modularity', status = 'primary', width=NULL, solidHeader=T, collapsible = TRUE,collapsed=FALSE, 
                        fluidRow( 
                            column(
                            width = 12,
                            HTML("Gene set coexpression: "),
                            textOutput("geneset_coexp"),
                            br(),
                        ),
                            column(
                            width = 12,
                            HTML("Gene set modularity (strength of coexpression relative to random gene sets of equal length): "),
                            textOutput("egad_roc")                          
                        )
                            # column(width=2,                          
                            #     uiOutput('downloadButton2')  
                            # )
                        )
                    ),
                    box(title = 'Functional enrichment of gene set', status = 'primary', width=NULL, solidHeader=T, collapsible = TRUE,collapsed=FALSE, 
                        fluidRow( 
                            column(
                            width = 12,
                            HTML("List of GO terms associated with input gene set"),
                            DT::dataTableOutput("egad_table")                          
                        )
                            # column(width=2,                          
                            #     uiOutput('downloadButton2')  
                            # )
                        )
                    )

                )
                )), # end of tab item enrich

        tabItem(   # start of data downlaod
            tabName = "download_data",
            fluidPage(   
                # Add custom CSS styling in the head
              tags$head(
                tags$style(HTML("
                  .custom-link {
                    color: #333333;
                    text-decoration: none;
                  }
                  .custom-link:hover {
                    color: #3c8dbc;
                    text-decoration: none;
                  }
                "))
              ),
                titlePanel('Downloading CoCoBLAST raw data'),
                HTML("We have mined NCBI's Sequence Read Archive to collect bulk transcriptomic data from over 7,000 studies and 360,000 samples spanning 142 species across the tree of life. This large-scale resource provides multiple file types for download, such as gene expression, coexpression and conservation matrices, all organized for easy access and analysis."),br(),br(),

                HTML("<h4>Browse files by category</h4>"), 
                HTML("Gene expression matrices (with CPM, TPM and RPKM-normalized values):
                    <a href='https://cocoblast.ccbr.utoronto.ca/files/expression/' target='_blank'>here</a>
                    "),
                br(),

                HTML("Gene coexpression matrices (one per species):
                    <a href='https://cocoblast.ccbr.utoronto.ca/files/networks/' target='_blank'>here</a>
                    "),
                br(),

                HTML("Gene coexpression conservation scores (for pairs of species):
                    <a href='https://cocoblast.ccbr.utoronto.ca/files/coexp_cons/' target='_blank'>here</a>
                    "),
                br(),

                HTML("Homologous gene sets (derived using eggNOG-mapper v2.1.12):
                    <a href='https://cocoblast.ccbr.utoronto.ca/files/supplement_data/ortholog_maps' target='_blank'>orthologs</a>,
<a href='https://cocoblast.ccbr.utoronto.ca/files/supplement_data/paralog_maps' target='_blank'>paralogs</a>
                    "),
                br(), br(),
                HTML("<h4>Browse files by species</h4>"),                              
                        fluidRow( 
                            column(
                            width = 12,
                            summary_table                                                    
                        ) 
                      )
                   

                )
            )  # end of tab item (data download)
        
    )   # end tabitems
)   # end dashboard body           


# build everything
ui <- shinyUI(fluidPage(
  tags$head(tags$link(rel="shortcut icon", href="new_logo.png")),
  tags$body(
      # tags$img(src = "cocoblast_cartoon1.png", width = '100%'),
                dashboardPage(header, sidebar, body))
))


# dashboardPage(header, sidebar, body)



