```{r }

listnameDir <- paste0(annotDir[[data]][[paste0(annot, "EnrichAnal")]][[ontology]],
                      RFLOMICS:::contrastName2contrastDir(listname),"/")
dir.create(path=listnameDir, recursive = TRUE, showWarnings = FALSE)

opts_chunk$set(
  fig.path=listnameDir
)

```

##### {.tabset}

<details>
<summary>**`r paste0(ifelse(!is.null(tag), paste0("[",tag,"] "), ""), listname)`**</summary>

<br>

```{r}

enrichRes <- 
  getEnrichRes(dataset.SE,
               featureListName = listname,
               from = annot, 
               database = ontology)
```

```{r}
log2FC_vect <- NULL
if (annot == 'DiffExp') {
  TopDEF <- getAnalysis(dataset.SE, 
                        name = paste0(annot, "Anal"), 
                        subName = "results")[["TopDEF"]]
  
  log2FC_vect <- TopDEF[[listname]]$logFC
  names(log2FC_vect) <- rownames(TopDEF[[listname]])
}

```

###### Dotplot

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

out <- NULL
for (domain in names(enrichRes)) {
  
  dataPlot <-  enrichRes[[domain]]
  if (nrow(dataPlot) == 0) next
  
  out <- c(out, paste0("\n* **", domain, ":**\n\n"))
  
  cmd <- paste0("p <- clusterProfiler::dotplot(dataPlot, showCategory = 15) + ",
                "ggtitle(paste0(listname, '\nDomain: ', domain, '\n(First 15 enriched terms)')); ",
                "print(p)")
  
  dotplot_CPR <-
    c(paste0(
      "```{r dotplot_CPR_",domain ,", fig.width = 15, fig.height = 7, fig.show = \"hold\"}"),
      cmd,
      "```")
  
  out <- 
    c(out, 
      knit_child(text = dotplot_CPR, envir = environment(), quiet=TRUE),
      "\n<hr/>\n")
}
asis_output(out)

```

###### Heatplot

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

out <- NULL
for (domain in names(enrichRes)) {
  
  dataPlot <-  enrichRes[[domain]]
  if (nrow(dataPlot) == 0) next
  
  out <- c(out, paste0("\n* **", domain, ":**\n\n"))
  
  cmd <- paste0("p <-  heatplot(dataPlot, showCategory = 15, foldChange = log2FC_vect) + ",
                "labs(fill=\"log2FC\") + ",
                "scale_fill_gradient2(low = \"blue\", mid = \"white\", high = \"red\", midpoint = 0) +",
                "theme(axis.text.y = element_text(size = 10)) + ",
                "ggtitle(paste0(listname, '\nDomain: ', domain, '\n(First 15 enriched terms)'));",
                "suppressMessages(print(p))# delete warnings for scale fill replacement")
  
  heatplot_CPR <- 
    c(paste0(
      "```{r heatplot_CPR_",domain ,", fig.width = 15, fig.height = 7, fig.show = \"hold\"}"),
      cmd, 
      "```")
  
  out <- 
    c(out, 
      knit_child(text = heatplot_CPR, envir = environment(), quiet=TRUE),
      "\n<hr/>\n")
}
asis_output(out)

```

###### Cnetplot

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

out <- NULL
for (domain in names(enrichRes)) {
  
  dataPlot <-  enrichRes[[domain]]
  if (nrow(dataPlot) == 0) next
  
  out <- c(out, paste0("\n* **", domain, ":**\n\n"))
  
  cmd <- paste0(
    "p <- cnetplot(dataPlot, showCategory = 15, foldChange = log2FC_vect, node_label = \"category\") +", 
    "guides(colour=guide_colourbar(title = \"log2FC\")) +",
    "scale_fill_gradient2(low = \"blue\", mid = \"white\", high = \"red\", midpoint = 0) +", 
    "ggtitle(paste0(listname, '\nDomain: ', domain, '\n(First 15 enriched terms)'));",
    "suppressMessages(print(p)) # delete warnings for scale fill replacement")
  
  CnetPlot_CPR <-
    c(paste0(
      "```{r CnetPlot_CPR_",domain ,", fig.width = 15, fig.height = 7, fig.show = \"hold\"}"),
      cmd,
      "```")
  
  out <- 
    c(out, 
      knit_child(text = CnetPlot_CPR, envir = environment(), quiet=TRUE),
      "\n<hr/>\n")
}
asis_output(out)

```


###### Table

```{r}
opts_chunk$set(
  fig.path=listnameDir
)
```


```{r}
dataPlot <- list()

for (domain in names(getEnrichRes(dataset.SE,
                                  from = annot, 
                                  database = ontology, 
                                  featureListName = listname))) {
  if (length(domain) != 0) {
    tmp <- getEnrichRes(dataset.SE,
                        from = annot, 
                        database = ontology, 
                        featureListName = listname,
                        domain = domain)
    tmp@result$domain <- rep(domain, dim(tmp@result)[1])
    dataPlot[[domain]] <- tmp@result[tmp@result$p.adjust < tmp@pvalueCutoff, ] 
    dataPlot[[domain]][["geneID"]] <- NULL
    dataPlot[[domain]][["qvalue"]] <- NULL
  }
}

# Bind results domain

if (length(dataPlot) != 0) {
  dataPlot.rbind <- Reduce(rbind, dataPlot)
  
  colKeep <- unlist(lapply(dataPlot.rbind, is.numeric))
  dataPlot.rbind[, colKeep] <- signif(dataPlot.rbind[, colKeep], 3)
  
  datatable(dataPlot.rbind, rownames = FALSE , class = 'cell-border stripe',
            options = list( pageLength = 6, scrollX = F, lengthChange = F))
}

```

```{r tableCPR, fig.width = 15, fig.height = 7, fig.show = "hold"}
for (domain in names(enrichRes)) {
  dataPlot <-  enrichRes[[domain]]
  write.table(dataPlot@result[dataPlot@result$p.adjust < dataPlot@pvalueCutoff, ],
              file=paste0(listnameDir,"Table_of_Enriched_terms_for_", 
                          domain,"_","pval_",
                          dataPlot@pvalueCutoff,".txt"),
              sep="\t",
              quote=FALSE,
              col.names=TRUE,
              row.names=FALSE)
}
```

##### {-}