---
title: "`r paste0('Your report from GeneTonic - ', project_id)`"
author: "`r paste0('GeneTonic happy_hour (v', utils::packageVersion('GeneTonic'), ')')`"
date: "`r Sys.Date()`"

output: 
  html_document:
    toc: true
    toc_float: true
    code_folding: show
    code_download: true
    number_sections: true
    df_print: kable
    theme: lumen
always_allow_html: yes
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  echo = TRUE, 
  warning = FALSE, 
  message = FALSE,
  error = TRUE
)
# knitr::opts_knit$set(
#   progress = FALSE, 
#   verbose = FALSE
# )
```


# Introduction - the input data

<!-- ideas: -->

<!-- - differentiate the content based on batch running vs generated at runtime? -->
<!-- - print out the values of input$... objects. So one can just repeat them ;) -->

This is an overview on the provided objects:

```{r echo = TRUE}
library(GeneTonic)
```


```{r}
# if (exists("reactive_values$mygenesets")) {
#   selected_genesets <- reactive_values$mygenesets
# } else {
#   selected_genesets <- mygenesets
# }
# 
# if (exists("reactive_values$mygenes")) {
#   selected_genes <- reactive_values$mygenes
# } else {
#   selected_genes <- mygenes
# }

if (usage_mode == "shiny_mode") {
  selected_genesets <- reactive_values$mygenesets
  selected_genes <- reactive_values$mygenes
  
  
  # picking from the reactive values
  dds <- reactive_values$dds
  res_de <- reactive_values$res_de
  res_enrich <- reactive_values$res_enrich
  annotation_obj <- reactive_values$annotation_obj
  
  intgroup <- input$exp_condition
  # checking that a group is provided
  if (is.null(input$exp_condition)) {
    # defaults to first column name in the colData
    intgroup <- colnames(colData(dds))[1]
  }
  
} else if (usage_mode == "batch_mode"){
  selected_genesets <- mygenesets
  selected_genes <- mygenes
  intgroup <- mygroup
}

selected_genesets
selected_genes
intgroup
```

If provided as a gtl object:

```{r}
if (!is.null(gtl)) {
  cat(describe_gtl(gtl))
}
```

Otherwise, these are the individual components as provided:

```{r echo = TRUE}
dds
res_de
head(res_enrich)
head(annotation_obj)
res_enrich <- get_aggrscores(res_enrich, res_de, annotation_obj)
```

## Parameter settings 

If running from shiny, it might be relevant to keep track of the parameters currently selected in the app, as they determine the look and content of what is displayed.

```{r}
if (usage_mode == "shiny_mode") {
  input$exp_condition
  input$n_genesets
  input$emap_colorby
  
  # print(shiny::reactiveValuesToList(input))
  # print(shiny::reactiveValuesToList(reactive_values))
} 
```

# A quick overview on the enrichment results

This section reports an interactive enrichment map for the results from the enrichment analysis, as an overview.

```{r}
library("visNetwork")
library("magrittr")
emap_graph <- enrichment_map(
        res_enrich = res_enrich,
        res_de = res_de,
        annotation_obj = annotation_obj,
        n_gs = 50,
        overlap_threshold = 0.1,
        scale_edges_width = 200,
        color_by = "z_score"
)
emap_graph

visNetwork::visIgraph(emap_graph) %>%
        visOptions(
          highlightNearest = list(
            enabled = TRUE,
            degree = 1,
            hover = TRUE
          ),
          nodesIdSelection = TRUE
        ) %>%
        visExport(
          name = "emap_network",
          type = "png",
          label = "Save enrichment map"
        )
```



# Content for the selected genes

The following genes were reported as bookmarked in the call to this report, either in batch or in the shiny usage mode.

```{r}
DT::datatable(annotation_obj[annotation_obj$gene_id %in% selected_genes, ])
```

For each of them, a plot for the expression values is displayed in the content that follows.

```{r}
lapply(selected_genes, function(arg) {
  GeneTonic::gene_plot(dds,gene = arg,intgroup = intgroup, 
                       annotation_obj = annotation_obj)})
```

# Content for the selected genesets

The following genesets were reported as bookmarked in the call to this report, either in batch or in the shiny usage mode.

```{r}
DT::datatable(res_enrich[res_enrich$gs_id %in% selected_genesets, ])
```

Some general visualization, with a focus on the genesets specified above, is displayed as a result of the following chunk.

```{r}
gs_mds(res_enrich, res_de, annotation_obj, gs_labels = selected_genesets)

gs_volcano(res_enrich, volcano_labels = selected_genesets)
```

## Geneset content, tabbed! {.tabset .tabset-fade}

Here is a heatmap for each bookmarked set.
Click on the tabset labels to navigate among each of the elements.

```{r echo = TRUE, results="asis"}
vst_data <- DESeq2::vst(dds) # or also have it passed as param

for (gs in selected_genesets) {
  corresponding_gs_desc <- res_enrich[gs, "gs_description"]
  cat("### ", corresponding_gs_desc, " {-}\n")
  
  gs_heatmap(vst_data, 
             res_de, 
             res_enrich, 
             annotation_obj, 
             geneset_id = gs, 
             cluster_columns = TRUE)
  
  cat(go_2_html(gs, res_enrich))
  cat("\n\n")
}
```


# About this report

This report has been generated via the `happy_hour()` function from the GeneTonic package.

You can extend and modify the template provided in the package, and provide the location of the custom version as a parameter to the call to `happy_hour()` (specifically, `input_rmd`).

If you use this report in your scientific work, please cite GeneTonic:

```{r}
citation("GeneTonic")
```


# Session info {-}

This is the output of the `sessionInfo()` command, reported for improving the reproducibility of the analysis.

```{r}
sessionInfo()
```

