---
title: "Global Report"
output:
  html_document:
    toc: true
    toc_depth: 2
    number_sections: true
    theme: flatly
params:
  de_results: NULL
  enrichment_results: NULL
  grn_object: NULL
  report_date: !r Sys.Date()
vignette: >
  %\VignetteIndexEntry{Template_report}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
library(ggplot2)
library(DT)
library(dplyr)
library(igraph)
library(ggraph)
library(knitr)
library(kableExtra)
library(ggrepel)
library(htmltools)
library(gridExtra)
#library(XYomics)

# fallback operator
`%||%` <- function(x, y) if (!is.null(x)) x else y
```

#  Overview

This is a global report built for **XYomics output on Single-cell data**.

**Date:** `r params$report_date`\
**Includes:** - Differential expression analysis (DEGs) - Pathway enrichment analysis - Protein-protein interaction networks analysis

------------------------------------------------------------------------

#  Differential Expression Results of categorized DEGs by cell types

```{r de-results, echo=F}


get_name <- function(df){
  for (i in seq_along(params$de_results)){

    name=names(params$de_results)[i]

    if (length(all.equal(df, params$de_results[[name]]))==1){
      
      name_df=name

    } 
  } 
  return(name_df)
}

render_de_table <-  function(df) {
    if (nrow(df) == 0) {
    return(tags$div(
      tags$h4(paste("DEGs Results -", name)),
      tags$p("No significant DEGs for this category.")
    ))
  }
  else
  {   name <- get_name(df) 
    return(tags$div(
      tags$h4(paste("DEGs Results -", name)),
      tags$p( datatable(df%>% mutate(across(ends_with("logFC"), ~round(.,digits=3))) %>% mutate(across(ends_with("FDR"), ~format(.,scientific=T,digits=3))),
            options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE)))
  )

  }

 
  
  
}

tagList(
  lapply(params$de_results, render_de_table)
)
```
## Volcano Plots by cell types and categories of DEGs

```{r volcano-plots , echo=FALSE,results='asis', fig.keep='all', fig.width=8, fig.height=6}


all_plots <- plot_volcano_deg(params$de_results)



for (set_name in names(all_plots)) {
  cat(sprintf("\n\n### Volcano Plot - %s\n\n", set_name))
  print(all_plots[[set_name]])
}
```

------------------------------------------------------------------------

# Enrichment / Pathway Analysis

```{r enrichment-tables, echo=FALSE}

render_enrichment_table <- function(df, name) {
  if (is.null(df)) {
    return(tags$div(
      tags$h4(paste("Pathway Enrichment -", name)),
      tags$p("No significant pathways for this category.")
    ))
  }
  else
  {  
    df=df %>% relocate(DEG_Type)
    return(tags$div(
    tags$h4(paste("Pathway Enrichment -", name)),
    tags$p(datatable(
      df %>% mutate_if(is.numeric, ~format(., scientific=T, digits=3)),
      options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE)))
  )
    
  }
  
  
}



tagList(lapply(seq_along(params$enrichment_results ), function(i) {
  name <- names(params$enrichment_results )[i] %||% paste("Set", i)
  sublist <-params$enrichment_results [[i]]
  combined_df <- do.call(rbind, lapply(names(sublist ), function(name) {
    df <- as.data.frame(sublist [[name]])
    if (nrow(df) == 0) return(NULL) 
    df$DEG_Type <- name
    return(df)
  }))


  render_enrichment_table(combined_df, name)
}))

```

## Dotplot of the pathways by cell types
```{r pathways visualization , echo = FALSE,  results='asis', fig.keep='all', fig.width=15, fig.height=7, message=FALSE}

all_plots <-plot_enrichment_dotplots(params$enrichment_results)



for (set_name in names(all_plots)) {
  cat(sprintf("\n\n### Volcano Plot - %s\n\n", set_name))
  print(all_plots[[set_name]])
}


```

# Protein-protein interaction network (PPI)

```{r grn-summary , echo = FALSE,  results='asis', fig.keep='all', fig.width=15, fig.height=10, message=FALSE}


all_plots <-plot_network_pipeline(params$grn_object, params$de_results)

for (set_name in names(all_plots)) {
  cat(sprintf("\n\n### Volcano Plot - %s\n\n", set_name))
  print(all_plots[[set_name]])
}

```

------------------------------------------------------------------------

# Session Info

```{r session-info}
# sessionInfo()
```

------------------------------------------------------------------------

### Auto-generated on `r Sys.time()` using `XYomics` reporting
