
```{r}

ont.title <- switch (ontology,
                     "GO" = {"Gene Ontology database"},
                     "KEGG" = {"KEGG database"},
                     "custom" = {"Custom annotation"}
)
```

### `r ont.title` {.tabset .tabset-fade .tabset-pills}

```{r}

MM.db <- 
  switch(
    ontology,
    "GO" = {
      db <- 
        getEnrichSettings(object   = dataset.SE, 
                          from     = "DiffExp", 
                          database = "GO")$OrgDb
      if(is.null(db))
        db <- 
          getEnrichSettings(object   = dataset.SE, 
                            from     = "CoExp", 
                            database = "GO")$OrgDb
      
      paste0("Gene Ontology ([GO](https://geneontology.org/)) from **", db, 
             "** annotation (version ", RFLOMICS:::.getPackageInfo(rflomics.MAE, db),").",
             "\n**enrichGO()** function from **ClusterProfilter** was used.")
    },
    "KEGG" = {
      keggRelease <- 
        getEnrichSettings(dataset.SE,
                          from = "DiffExp", 
                          database = "KEGG")$keggRelease
      if(is.null(keggRelease))
        keggRelease <- 
          getEnrichSettings(dataset.SE,
                            from = "CoExp", 
                            database = "KEGG")$keggRelease
      
      paste0("Kyoto Encyclopedia of Genes and Genomes ",
             "([KEGG](https://www.genome.jp/kegg/)) (release ", keggRelease,").",
             "\n**enrichKEGG()** function from ClusterProfilter was used.")
    },
    "custom" = {
      paste0("Provided by user.",
             "\n**enricher()** function from ClusterProfilter was used.")}
  )

```

*`r MM.db`*

<br>

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

out <- NULL
for (annot in c("DiffExp", "CoExp")){
  
  EnrichAnal <- getAnalysis(dataset.SE, 
                            name = paste0(annot, "EnrichAnal"), 
                            subName = ontology)
  
  # if (!isTRUE(annot.list[[data]][[ontology]][[paste0(annot, "EnrichAnal")]]))
  #   next
    
  if (is.null(EnrichAnal)) next
  
  # tabset for each list type
  out <- 
    c(out, 
      paste0("\n#### From ",
             ifelse(annot == "DiffExp", 
                    "differentially expressed ", "co-expressed "), 
             variableName, " lists\n"),
      paste0("\n*Pvalue cut-off: ",
             getEnrichSettings(dataset.SE, from = annot, database = ontology)$pvalueCutoff,
             "*\n"))
  
  # summary
  out <- 
    c(out, 
      paste0("\n* **Summary of the results for all the ",
             ifelse(annot == "DiffExp", "contrasts:", "clusters:"),
             "**\n"))
  
  # table
  sumORA.ont <- sumORA(dataset.SE, from = annot, database = ontology)
  index <- names(sumORA.ont)[-1]
  if ("no-domain" %in% names(sumORA.ont)[-1]) {
    names(sumORA.ont) <- 
      c(names(sumORA.ont)[1], ontology)
    index <- ontology
  }
  
  ## add tag to summary table 
  if (annot == "DiffExp") {
    tag <- 
      validContrasts[which(validContrasts$contrastName %in% rownames(sumORA.ont)),]$tag
    sumORA.ont <- cbind(tag, sumORA.ont)
  }
  
  write.table(sumORA.ont, 
              file = paste0(annotDir[[data]][[paste0(annot, "EnrichAnal")]][[ontology]], 
                            "summay_stat.txt"),
              sep = "\t", quote = FALSE, col.names = TRUE, row.names = FALSE)
  
  DT.child <-  
    c("```{r}",
      "datatable(sumORA.ont, rownames = FALSE , class = 'cell-border stripe',
                 options = list(pageLength = 6, scrollX = FALSE, dom = 'tip'))",
      "```")
  out <- c(out, knit_child(text = DT.child, envir = environment(), quiet=TRUE))
  
  # error messages
  errorMessages <- 
    getAnalysis(dataset.SE, 
                name = paste0(annot, "EnrichAnal"), 
                subName = ontology)$errors
  
  text.help = ""
  if(any(sumORA.ont == 0))
    text.help <- c(
      paste0("0: no significantly enriched ", variableName))
  
  if(length(errorMessages) != 0){
    text.help <- 
      paste0(text.help, "\n", "NA: \n", 
             paste(unique(unlist(errorMessages)), collapse = "\n"))
  }
  
  if(text.help != ""){
    DT.child <-  
      c("```",
        text.help,
        "```")
    out <- c(out, knit_child(text = DT.child, envir = environment(), quiet=TRUE))
    
  }
  # Results per list
  sumORA.ont <- 
    sumORA.ont[rowSums(sumORA.ont[index], na.rm = TRUE) != 0,]
  
  if(nrow(sumORA.ont) == 0) next
  
  out <- 
    c(out, 
      paste0("\n* **Results per ",
             ifelse(annot == "DiffExp", "contrast:", "cluster:"), "**\n"),
      paste0("\n*Please click on the arrows to scroll down the results and click on the figure to zoom*\n"))
  
  for (listname  in rownames(sumORA.ont)){
    tag <- NULL
    if(annot == "DiffExp")
      tag <- sumORA.ont[which(sumORA.ont$Contrast == listname),]$tag
    out <- c(out, knit_child(
      paste0(path.package("RFLOMICS"), "/RFLOMICSapp/",
             "report_06_enrichmentORA_per_list_CPR.Rmd"), quiet = TRUE))
  }
}
asis_output(out)

```
