---
title: "NetSurvProx: Pathway Analysis Dashboard"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    theme: lumen
params:
  inputFile: NULL
  header: TRUE
  useKeggAPI: TRUE
  nodesCols: !r c("#5C7997", "#F5C59F")
  diseaseNodes: FALSE
  disease_file: NULL
  top_percent: 20
  batch_size: 10
  dataset: "org.Hs.eg.db"
  organism: "hsa"
  background: NULL
  min_genes: 2
  top_n: 10
  rds_path: NULL
---
  
```{r setup, include=FALSE}

library(igraph)
library(visNetwork)
library(htmltools)
library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
library(plotly)

# This dashboard is created from PathwayDashboard()
# using the file network_data.rds saved

rds_path <- params$rds_path

if (is.null(rds_path) || !file.exists(rds_path)) {
  stop("Network data file not found.", call. = FALSE)
}

data <- readRDS(rds_path)

nodesCols <- params$nodesCols

g           <- data$g
edge_info   <- data$edge_info
all_syms    <- data$all_genes
conn_syms   <- data$conn_genes
node_cols   <- data$node_colours
background  <- data$background
min_genes   <- data$min_genes
top_n       <- data$top_n
legend_info <- data$legend_info
pathway_df  <- data$pathway_df

if (!is.null(legend_info$legend_label)) legend_info$legend_label <- sub("\\s*-\\s*[^-]*$", "", legend_info$legend_label)

if (!is.null(pathway_df$name)) pathway_df$name <- sub("\\s*-\\s*[^-]*$", "", pathway_df$name)

```

Partial Network {data-icon="fa-table"}
=====================================
  
  Row 
-------------------------------------
  
### Not-Isolated Genes
  
```{r, echo=FALSE}

if(vcount(g) > 0){
  
  node_colors  <- node_cols$n_colours[match(conn_syms, all_syms)]
  node_borders <- node_cols$n_borders[match(conn_syms, all_syms)]
  
  nodes_df <- data.frame(
    id    = conn_syms,
    label = conn_syms,
    color.background = node_colors,
    color.border     = node_borders,
    shape = "ellipse",
    stringsAsFactors = FALSE)

  path_lookup <- data.frame(
    code  = legend_info$legend_code,
    title = legend_info$legend_label,
    stringsAsFactors = FALSE)
  
  edges_df <- merge(edge_info, path_lookup, by.x = "path", by.y = "code", all.x = TRUE)
  edges_df$pathway <- edges_df$path
  edges_df$label   <- as.character(match(edges_df$title, unique(edges_df$title)))
  

  nodes_df$pathway <- sapply(nodes_df$id, function(x) {
    unique(edges_df$path[edges_df$from == x | edges_df$to == x])[1]})
    
  legend_nodes <- list(
    list(label = "Mapped",
         shape = "ellipse", 
         color = list(
           background = nodesCols[1],
           border = nodesCols[1]),
         font = list(
           color = "#FFFFFF"),
         shadow = list(
           enabled = TRUE,
           size = 10)))
  
  if (!is.null(params$diseaseNodes) && params$diseaseNodes) {
    legend_nodes <- c(list(
      list(
        label = paste0("Top ", params$top_percent, "%"),
        shape = "ellipse",
        color = list(
          background = nodesCols[2],
          border     = nodesCols[2]),
        font = list(
          color = "#FFFFFF"),
        shadow = list(
          enabled = TRUE,
          size    = 10))), 
      legend_nodes)}
  
  visNetwork::visNetwork(nodes_df, edges_df) %>%
    visNetwork::visNodes(
      physics = FALSE,
      font    = list(
        size  = 20,
        color = "#FFFFFF"),
      size = 30,
      shadow = list(
        enabled = TRUE,
        size    = 10)) %>%
    visNetwork::visEdges(
      smooth = list(
        enabled = TRUE,
        type    = 'dynamic',
        physics = FALSE)) %>%
    visNetwork::visIgraphLayout(layout = "layout_in_circle") %>%
    visNetwork::visLegend(
      useGroups = FALSE,
      addNodes  = legend_nodes,
      width     = 0.2) %>%
    visNetwork::visExport(
      type  = "pdf",
      name  = "Partial_Network",
      label = "Download Partial Network",
      style = "position: relative; top: -30px; left: 2px; z-index: 1000;") %>%
    visNetwork::visOptions(
      highlightNearest = TRUE,
      nodesIdSelection = TRUE)
  } else {
    stop("No genes connected to any pathway.")}

```

### Pathway Legend {data-width=400}

```{r, echo=FALSE, results='asis'}

if (!is.null(legend_info) &&
    !is.null(legend_info$legend_code) &&
    length(legend_info$legend_code) > 0) {
  legend_df <- data.frame(
    legend_code   = legend_info$legend_code,
    legend_label  = legend_info$legend_label,
    legend_colour = legend_info$legend_colour,
    legend_count  = legend_info$legend_count,
    stringsAsFactors = FALSE)
  
  html <- htmltools::tags$div(
    style = "height:500px; width:700px; overflow-y; 
    auto; font-size:17px; line-height:1; padding-left:10px;",
    lapply(seq_len(nrow(legend_df)), function(i){
      htmltools::tags$p(style=paste0("color:", legend_info$legend_colour[i], "; 
                          margin:5px 10px; font-weight:bold;"),
             paste0(
               legend_info$legend_count[i],
               ". ",
               legend_info$legend_label[i],
               " (",
               legend_info$legend_code[i],
               ")"))}))
  htmltools::HTML(as.character(html))
} else {
  stop("Pathway legend not available.")}

```

Full Network {data-icon="fa-th"}
=====================================
  
  Row 
-------------------------------------
  
### All Genes
  
```{r, echo=FALSE}

isolated <- setdiff(all_syms, conn_syms)

nodes_all <- data.frame(
  id    = all_syms,
  label = all_syms,
  color.background = node_cols$n_colours,
  color.border     = node_cols$n_borders,
  shape = "ellipse",
  color.highlight.background = node_cols$n_colours,
  stringsAsFactors = FALSE)

path_lookup <- data.frame(
  code  = legend_info$legend_code,
  title = legend_info$legend_label,
  stringsAsFactors = FALSE)

edges_all <- merge(edge_info, path_lookup, by.x = "path", by.y = "code", all.x = TRUE)

if (is.null(edges_all) || nrow(edges_all) == 0) {
  edges_all <- data.frame(
    from  = character(0),
    to    = character(0),
    label = character(0),
    color = character(0),
    title = character(0),
    stringsAsFactors = FALSE)
} else {
  edges_all$label <-  as.character(match(edges_df$title, unique(edges_df$title)))}

legend_nodes <- list(
  list(
    label = "Mapped",
    shape = "ellipse",
    color = list(
      background = nodesCols[1],
      border     = nodesCols[1]),
    font = list(
      color = "#FFFFFF"),
    shadow  = list(
      enabled = TRUE,
      size = 10)),
  list(
    label = "Not Mapped",
    shape = "ellipse",
    color = list(
      background = "#FFFFFF",
      border     = "#e6e4df"),
    shadow = list(
      enabled = TRUE,
      size = 10)))

if (!is.null(params$diseaseNodes) && params$diseaseNodes) {
  legend_nodes <- c(list(
    list(
      label = paste0("Top ", params$top_percent, "%"),
      shape = "ellipse",
      color = list(
        background = nodesCols[2],
        border = nodesCols[2]),
      font = list(
        color = "#FFFFFF"),
      shadow = list(
        enabled = TRUE,
        size = 10))), 
    legend_nodes)}

nodes_all$font.color <- ifelse(nodes_all$color.background == "#FFFFFF", "#000000", "#FFFFFF")

visNetwork::visNetwork(nodes_all, edges_all) %>%
  visNetwork::visNodes(
    physics = FALSE,
    font = list(size = 20),
    size = 30,
    shadow = list(
      enabled = TRUE,
      size = 10)) %>%
  visNetwork::visEdges(
    smooth = list(
      enabled = TRUE,
      type    = 'dynamic',
      physics = FALSE)) %>%
  visNetwork::visIgraphLayout(layout = "layout_nicely") %>%
  visNetwork::visLegend(
    useGroups = FALSE,
    addNodes  = legend_nodes,
    width = 0.2) %>%
  visNetwork::visExport(
    type  = "pdf",
    name  = "Full_Network",
    label = "Download Full Network",
    style = "position: relative; top: -30px; left: 2px; z-index: 1000;") %>%
  visNetwork::visOptions(
    highlightNearest = TRUE,
    nodesIdSelection = TRUE)
   
```

Pathway Enrichment {data-icon="fa-th"}
=====================================  

  Row 
-------------------------------------

### Top `r top_n` Barplot Enrichment

```{r, echo=FALSE, message=FALSE, fig.height=5, fig.width=8}

# This is created from Enrichment()

default_cols <- c("#5C7997", "#F5C59F")
current_cols <- params$nodesCols

bar_color_yes <- if(identical(current_cols, default_cols)) "#7DAE9B" else current_cols[1]
bar_color_no  <- "#e6e4df"

enrich_res <- Enrichment(
  genes = conn_syms,
  pathway_df = pathway_df,
  background_genes = background,
  min_genes = min_genes,
  top_n = top_n,
  out_file = NULL)

gene_info <- pathway_df %>%
  dplyr::filter(pathway %in% enrich_res$bar_data$pathway) %>%
  dplyr::group_by(pathway) %>%
  dplyr::summarize(
    genes = paste(unique(gene), collapse = ", "),
    tooltip_genes = stringr::str_wrap(genes, width = 40) %>% gsub("\n", "<br>", .),
    .groups = "drop")

res <- dplyr::left_join(enrich_res$bar_data, gene_info, by = c("pathway"))

p <- ggplot2::ggplot(res, aes(x = reorder(name , nGenes), y = nGenes, fill = highlight, text = paste0("Genes: ", genes))) +
     ggplot2::geom_bar(stat = "identity", width = 0.7) + 
     ggplot2::coord_flip() +
     ggplot2::scale_fill_manual(values = c("No" = bar_color_no, "Yes" = bar_color_yes), name = "Enriched:") +
     ggplot2::scale_y_continuous(breaks = pretty_breaks(n = max(enrich_res$bar_data$nGenes)), 
                        labels = function(x) as.integer(x)) +
     ggplot2::labs(x = "", y = "Number of genes") +
     ggplot2::theme_minimal() +
     ggplot2::theme(legend.position = "none") 

plotly::ggplotly(p, tooltip = "text", width = 700, height = 500) %>%
  plotly::layout(
    hoverlabel = list(
      bgcolor     = "#FFFFFF",    
      font        = list(color = "#000000", size = 9),
      bordercolor = "#E6E4DF",
      namelength  = -1 
    ),
    autosize = TRUE,
    margin = list(l = 100) 
  ) %>%
  plotly::config(
    modeBarButtonsToRemove = c("zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d"),
    displaylogo = FALSE,
    displayModeBar = "hover"
  )

```

### Top `r top_n` Dotplot Enrichment with P-Value (Adjusted)

```{r, echo = FALSE, message = FALSE, fig.height = 5, fig.width = 8}   

# This is created from Enrichment()

low_col  <- if(identical(params$nodesCols, c("#5C7997", "#F5C59F"))) "#8ABFE7" else params$nodesCols[1]
high_col <- if(identical(params$nodesCols, c("#5C7997", "#F5C59F"))) "#5C7997" else params$nodesCols[2]

q <- ggplot2::ggplot(res, aes(
  x = nGenes, y = reorder(name, nGenes), color = padj, size = nGenes,
  text = paste0("<b>Pathway:</b> ", name, 
                "<br><b>padj:</b> ", sprintf("%.4e", padj), 
                "<br><b>Genes:</b> ", tooltip_genes))) +
     ggplot2::geom_point() +
     ggplot2::scale_color_gradient(low = low_col, high = high_col) +
     ggplot2::labs(x = "Number of genes", y = "") +
     ggplot2::theme_minimal()

plotly::ggplotly(q, tooltip = "text", width = 700, height = 500) %>%
  plotly::layout(
    hoverlabel = list(
      bgcolor     = "#FFFFFF",    
      font        = list(color = "#000000", size = 9),  
      bordercolor = "#E6E4DF",
      namelength  = -1
    ),
    autosize = TRUE,
    margin = list(l = 100)
  ) %>%
  plotly::config(
    modeBarButtonsToRemove = c("zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d"),
    displaylogo = FALSE,
    displayModeBar = "hover"
  )

```
