#' Identify gained/lost RNA populations between treatment and control conditions
#'
#' @description Identify unique sRNA or mRNA populations within a set of 
#' samples, typically within the same condition, compared to the other samples 
#' in the analysis. This can be known as lost or gained populations due to 
#' a treatment. 
#'
#' @details
#' The function selects RNA which are unique to a given
#' condition and absent in the samples within the other condition(s). 
#' For instance, a treatment might encourage the production of unique sRNAs 
#' which are not produced in the control samples. The function can also select
#' the unique populations which show statistical significance, based on a 
#' adjusted p-value cutoff. This must have been calculated previously, see 
#' [mobileRNA::RNAdifferentialAnalysis()] function. 
#'
#' If users are working with a chimeric system, utilise the `chimeric=TRUE`
#' parameter and state `genome.ID` and `controls` parameter variables. This will
#' remove any potential mapping errors which could lead to false 
#' interpretation. 
#' 
#' 
#' @param data data.frame; generated by [mobileRNA::RNAimport()]
#'
#' @param conditions character; containing names of samples within 
#' conditions to locate unique sRNA clusters. 
#'
#' @param statistical logical; If TRUE, will undertake statistical filtering 
#' based on the adjusted p-value cutoff stated by `alpha`. 
#' Default setting `statistical=FALSE`. Requires presence of columns 
#' containing statistical data. To filter by the adjusted p-value, a 
#' column named `padjusted` must be present. See 
#' [mobileRNA::RNAdifferentialAnalysis()] to calculate statistical values.
#'
#' @param alpha numeric; user-defined numeric value to represent the adjusted 
#' p-value threshold to define statistical significance. Defaults setting 
#' `alpha=0.05`. Returns sRNA clusters or mRNA with adjusted p-values equal 
#' or lower than the threshold value.
#'
#'@param chimeric logical; state whether system is chimeric containing multiple 
#'genomes/genotypes. 
#'
#'@param controls character; vector of control condition sample names. 
#'
#'@param genome.ID character; chromosome identifier of the genome representing 
#'either the origin of mobile molecules or the other genome in the chimeric 
#'system.
#'
#'@param dual logical; works in corporation when `chimeric=TRUE` and removes 
#'sRNA clusters mapped to the genome of mobile molecules. 
#'
#' @return A subset of the supplied data and prints summary metric of 
#' results including:
#' 
#' - the total number of sRNA clusters or mRNA in the data set 
#' - the number & percentage of unique sRNA clusters or mRNA to your condition
#' - the samples in the condition
#'
#' @examples
#'
#' data("sRNA_data")
#'
#' # Select sRNA clusters only in the heterograft samples (ie. treatment)
#' 
#' heterograft_pop <- RNApopulation(data = sRNA_data, 
#'                                  conditions = c("heterograft_1", 
#'                                                 "heterograft_2", 
#'                                                 "heterograft_3"))
#' @export
#' @importFrom dplyr %>%
#' @importFrom dplyr filter
#' @importFrom dplyr select
#' @importFrom tidyselect starts_with
#' @importFrom stats na.omit
RNApopulation <- function(data,conditions,statistical = FALSE,alpha = 0.05,
                          chimeric = FALSE, controls = NULL, 
                          genome.ID = NULL, dual = TRUE){
  
  if (!base::inherits(data, c("matrix", "data.frame", "DataFrame"))) {
    stop("data must be an object of class matrix, data.frame, DataFrame")
  }
  if (base::missing(conditions) || !base::inherits(conditions, "character")) {
    stop("Please specify a character vector storing names of control
               replicates")
  }
  
  conditions_cols <-  data %>% dplyr::select(paste0("Count_", conditions))
  opposite_cols <- data %>% 
    dplyr::select(dplyr::starts_with("Count_")) %>%
    dplyr::select(!colnames(conditions_cols))
  if(chimeric){
    data <- .remove_mapping_errors_V2(data = data,controls = controls, 
                                      genome.ID = genome.ID)
    if(dual == FALSE){
      data <- data %>% dplyr::filter(!grepl(genome.ID,chr))
    }
  } 
  if(chimeric == FALSE && !is.null(genome.ID)){
    data <- data %>% dplyr::filter(!grepl(genome.ID,chr))
  }
  output <- data[0,]
  for(i in seq_len(nrow(data))){
    sum_conditions <- sum(stats::na.omit(as.numeric(data[
      i,colnames(conditions_cols)],na.rm=TRUE)))
    sum_opposite <- sum(stats::na.omit(as.numeric(data[
      i,colnames(opposite_cols)],na.rm=TRUE)))
    if(sum_opposite == 0 && sum_conditions > 0){
      output <- rbind(output, data[i,])
      }
  }
    if (statistical) {
      if (!"padjusted" %in% colnames(res)) {
        stop("Column 'padjusted' not found in the data frame.
         Please refer to the vignette.")
      }
        res <- output %>% filter(padjusted <= alpha)
        # stats
        n_up <- sum(res[, "log2FoldChange"] > 0)
        n_down <- sum(res[, "log2FoldChange"] < 0)
        percent_up <- (n_up / nrow(res)) * 100
        percent_down <- (n_down / nrow(res)) * 100
        percent <- (nrow(res) / nrow(conditions_cols)) * 100
        
        out <- c(
          paste("Comparison :" ,unique(res$comparision.order), "\n"),
          paste("out of", nrow(conditions_cols), "sRNA clusters in the dataset \n"),
          paste("adjusted p-value < ", alpha),
          paste("unique sRNA clusters :", nrow(res),",", round(percent, 1), "% \n"),
          paste("samples :", paste(conditions, collapse = ", "),"\n", "\n" ),
          paste("LFC > 0 (higher) :", n_up, ",", round(percent_up, 1), "%"),
          paste("LFC < 0 (lower)  :", n_down, ",", round(percent_down, 1), "%"))
          
    } else
      if (statistical == FALSE){
        res <- output
        # stats
        if ("log2FoldChange" %in% colnames(res)){
          n_up <- sum(res[, "log2FoldChange"] > 0)
          n_down <- sum(res[, "log2FoldChange"] < 0)
          percent_up <- (n_up / nrow(res)) * 100
          percent_down <- (n_down / nrow(res)) * 100
          percent <- (nrow(res) / nrow(conditions_cols)) * 100
          
          out <- c(
            paste("Comparison :" ,unique(res$comparision.order), "\n"),
            paste("out of", nrow(conditions_cols), "sRNA clusters in the dataset \n"),
            paste("unique sRNA clusters :", nrow(res),",", round(percent, 1), "% \n"),
            paste("samples :", paste(conditions, collapse = ", "),"\n" ),
            paste("--- No statistical cutoff was implemented.", "\n", "\n"),
            paste("LFC > 0 (higher) :", n_up, ",", round(percent_up, 1), "%"),
            paste("LFC < 0 (lower)  :", n_down, ",", round(percent_down, 1), "%"))
          
        } else 
          if (!"log2FoldChange" %in% colnames(res)){
            percent <- (nrow(res) / nrow(conditions_cols)) * 100
            
            out <- c(
              paste("Comparison :" ,unique(res$comparision.order), "\n"),
              paste("out of", nrow(conditions_cols), "sRNA clusters in the dataset \n"),
              paste("unique sRNA clusters :", nrow(res),",", round(percent, 1), "% \n"),
              paste("samples :", paste(conditions, collapse = ", "),"\n" ),
              paste("--- No statistical cutoff was implemented."))
              
          }
      }
  
  methods::show(cat(out, collapse = " "))
  return(res)
}
