#' Enrichment_barplot
#'
#' Barplot representing the top up-regulated or down-regulated significant pathways
#'
#' @param Enrich A list of enrichment tables for up and down-regulated genes in the different enrichR databases.
#' Output of Enrichment.R function for one DGE experiment.
#' @param enrich.databases Vector of EnrichR databases to consider. These databases must be present in the Enrich list.
#' @param p_adj Double. Minimum Adjusted pvalue threshold for the enrichment
#' @param num_term Double. Number of up-regulated and dw-regulated terms to represent
#' @param cond String. Title of the plot.
#' @param plot Logical. If TRUE save plot as pdf.
#' @return bar plot of significant pathways.
#' @examples
#' \dontrun{
#' dbs <- c("GO_Biological_Process_2021")
#' dfList <- list()
#' dfList[["fdr_up"]]$GO_Biological_Process_2021 <- data.frame(
#'   Term = c("peripheral nervous system neuron differentiation (GO:0048934)",
#'            "apoptotic chromosome condensation (GO:0030263)",
#'            "negative regulation of CD4-positive, alpha-beta T cell differentiation (GO:0043371)"),
#'   Overlap = c("1/5", "1/5", "1/5"),
#'   P.value = c(0.0007498315, 0.0007498315, 0.0007498315),
#'   Adjusted.P.value = c(0.00893491, 0.00893491, 0.00893491),
#'   Old.P.value = c(0, 0, 0),
#'   Old.Adjusted.P.value = c(0, 0, 0),
#'   Odds.Ratio = c(2499.125, 2499.125, 2499.125),
#'   Combined.Score = c(17982.86, 17982.86, 17982.86),
#'   Genes = c("RUNX1", "TOP2A", "RUNX1"))
#' dfList[["fdr_down"]]$GO_Biological_Process_2021 <- data.frame(
#'   Term = c("skin morphogenesis (GO:0043589)",
#'            "skin development (GO:0043588)",
#'            "collagen fibril organization (GO:0030199)"),
#'   Overlap = c("2/7", "2/80", "2/89"),
#'   P.value = c(3.149296e-07, 4.727687e-05, 5.856991e-05),
#'   Adjusted.P.value = c(1.291211e-05, 8.004554e-04, 8.004554e-04),
#'   Old.P.value = c(0, 0, 0),
#'   Old.Adjusted.P.value = c(0, 0, 0),
#'   Odds.Ratio = c(7996.8000, 510.7436, 457.7011),
#'   Combined.Score = c(119719.427, 5086.745, 4460.430),
#'   Genes = c("COL1A1;COL1A2", "COL1A1;COL1A2", "COL1A1;COL1A2"))
#' Enrichment_barplot(dfList,
#'                    enrich.databases = dbs,
#'                    p_adj = 0.01, num_term = 3, cond = "UP")
#'}
#' @family functional-annotation functions
#' @family plot functions
#' @import knitr
#' @importFrom stringr str_replace
#' @importFrom ggplot2 ggplot geom_bar aes scale_fill_gradient scale_x_discrete labs coord_flip
#' @importFrom utils head
#' @importFrom grDevices pdf dev.off
#' @export


Enrichment_barplot <- function(Enrich,
                               enrich.databases  = c("GO_Biological_Process_2021",
                                                     "GO_Cellular_Component_2021",
                                                     "GO_Molecular_Function_2021"),
                               p_adj = 0.05, num_term = 10, cond = "UP",
                               plot = FALSE) {

  enrichR.table <- data.frame()

  # check if Enrich contains enrich.databases

  if (cond == "UP") {
    enrich_list <- Enrich[["fdr_up"]]

  } else if (cond == "DOWN") {
    enrich_list <- Enrich[["fdr_down"]]
  }

  if (length(setdiff(enrich.databases, names(enrich_list))) > 0) {
    warning(setdiff(enrich.databases, names(enrich_list)), " not present in your Enrichment analysis.")
    enrich.databases <- intersect(enrich.databases, names(enrich_list))
  }

  if (length(enrich.databases) == 0) {
    stop("Selected Enrich databases not present in your enrichment analysis.")
  }

  for (dat in enrich.databases) {
    Table <- enrich_list[[dat]]
    enrichR.table <- rbind(enrichR.table, Table)
  }

  row.names(enrichR.table) <- enrichR.table$Term

  fx <- function(x) eval(parse(text = enrichR.table[x, ]$Overlap))

  p <- enrichR.table[enrichR.table$Adjusted.P.value < p_adj, "Term"]

  if (length(p) > 0) { # Discarding the not-significant results (to avoid errors)
    pathways.dataframe <- data.frame(
      Pathway = p,
      gene.ratio = vapply(p, fx, FUN.VALUE = numeric(1)),
      p.value = enrichR.table[p, ]$P.value,
      p.value.adj = enrichR.table[p, ]$Adjusted.P.value
    )
    # Formatting the dataframe for the plot
    pathways.dataframe <- pathways.dataframe[order(pathways.dataframe$p.value.adj), ]
  }

  # N Top significant pathways

  top_sig <- head(pathways.dataframe[seq_len(num_term), ], num_term)

  # Significant pathway barplot

  top_sig$Log10Adj.P.value <- -log10(top_sig$p.value.adj)

  top_sig$Pathway <- stringr::str_replace(top_sig$Pathway, "\\s*\\([^\\)]+\\)", " ")

  top_sig <- top_sig[order(top_sig$gene.ratio), ]

  p_top_sig <- ggplot(top_sig, ggplot2::aes(x = Pathway, y = gene.ratio, fill = Log10Adj.P.value)) +
    geom_bar(stat = "identity") +
    scale_fill_gradient(low = "blue", high = "red",  name = "-Log10(p.adj.value)") +
    scale_x_discrete(limits = top_sig$Pathway) +
    labs(title = cond) +
    coord_flip()

  if (plot) {
    pdf("Top_sig_Pathways_barplot.pdf", 10, 5)
    p_top_sig
    dev.off()
  }

  Pathway <- gene.ratio <- Log10Adj.P.value <- NULL

  return(p_top_sig)

}
