#' Plot mCSEA results
#'
#' Generate an enrichment plot
#'
#' @param rank A named numeric vector with the ranking statistic of each CpG
#' site
#' @param mCSEAResults The object generated by mCSEATest function
#' @param regionType The region type to be represented. Must be one of
#' "promoters", "genes", "CGI" or "custom"
#' @param dmrName The DMR of interest to be represented (e.g. gene name,
#' CGI name...)
#'
#' @return 'NULL'
#'
#' @author Jordi Martorell Marugán, \email{jordi.martorell@@genyo.es}
#'
#' @seealso \code{\link{rankProbes}}, \code{\link{mCSEATest}},
#' \code{\link{mCSEAPlot}}
#'
#' @references Subramanian, A. et al (2005). \emph{Gene set enrichment analysis:
#'  A knowledge-based approach for interpreting genome-wide expression profiles}
#'  . PNAS 102, 15545-15550.
#'
#' @examples
#' \dontrun{
#' library(mCSEAdata)
#' data(mcseadata)
#' myRank <- rankProbes(betaTest, phenoTest, refGroup = "Control")
#' set.seed(123)
#' myResults <- mCSEATest(myRank, regionsTypes = "promoters",
#' platform = "EPIC")
#' }
#' data(precomputedmCSEA)
#' mCSEAPlotGSEA(myRank, myResults, "promoters", "CLIC6")
#' @export


mCSEAPlotGSEA <- function(rank, mCSEAResults, regionType, dmrName){

    # Check input objects
    if (any(class(mCSEAResults) != "list" | length(mCSEAResults) < 2)){
        stop("mCSEAResults must be the object generated
            by mCSEATest function")
    }

    if (class(dmrName) != "character"){
        stop("dmrName must be a character object")
    }

    # Get the appropiate association

    regionType <- match.arg(regionType,
                            choices=c("promoters", "genes", "CGI", "custom"))

    if(regionType == "promoters") {
        assoc <- mCSEAResults[["promoters_association"]]
    }

    else if(regionType == "genes") {
        assoc <- mCSEAResults[["genes_association"]]
    }

    else if(regionType == "CGI") {
        assoc <- mCSEAResults[["CGI_association"]]
    }

    else if(regionType == "custom") {
        assoc <- mCSEAResults[["custom_association"]]
    }

    if (!dmrName %in% names(assoc)){
        stop("dmrName name is not in the provided mCSEA results")
    }

    fgsea::plotEnrichment(assoc[[dmrName]], rank) + ggplot2::labs(title=dmrName)
}
