#' Plot the MBS contexts
#'
#' @details
#' Plots the number of MBS per MBS length per sample.
#' It takes a tibble with counts as its input. This tibble can be generated by count_mbs_contexts
#' Each sample is plotted in a separate facet.
#' The same y axis can be used for all samples or a separate y axis can be used.
#'
#' @param counts A tibble containing the number of MBS per MBS length.
#' @param same_y A boolean describing whether the same y axis should be used for all samples.
#'
#' @return A ggplot figure.
#'
#' @examples
#' ## Get The mbs counts
#' ## See 'count_mbs_contexts()' for more info on how to do this.
#' mbs_counts <- readRDS(system.file("states/blood_mbs_counts.rds",
#'   package = "MutationalPatterns"
#' ))
#'
#' ## Plot contexts
#' plot_mbs_contexts(mbs_counts)
#'
#' ## Use a different y axis for all samples.
#' plot_mbs_contexts(mbs_counts, same_y = FALSE)
#' @import ggplot2
#' @importFrom magrittr %>%
#' @family MBS
#'
#' @seealso \code{\link{count_mbs_contexts}}
#'
#' @export
plot_mbs_contexts <- function(counts, same_y = TRUE) {

  # These variables use non standard evaluation.
  # To avoid R CMD check complaints we initialize them to NULL.
  count <- size <- NULL

  # Make data long
  counts <- counts %>%
    as.data.frame() %>%
    tibble::rownames_to_column("size") %>%
    tidyr::pivot_longer(-size, names_to = "sample", values_to = "count") %>%
    dplyr::mutate(
      size = factor(size, levels = unique(size)),
      sample = factor(sample, levels = unique(sample))
    )

  # Count nr. muts
  nr_muts <- counts %>%
    dplyr::group_by(sample) %>%
    dplyr::summarise(nr_muts = round(sum(count)))

  # Create facets
  if (same_y) {
    facet_scale <- "fixed"
  } else {
    facet_scale <- "free_y"
  }

  facet_labs_y <- stringr::str_c(nr_muts$sample, " (n = ", nr_muts$nr_muts, ")")
  names(facet_labs_y) <- nr_muts$sample

  # Create plot
  fig <- ggplot(counts, aes(x = size, y = count, fill = size)) +
    geom_bar(stat = "identity") +
    facet_grid(sample ~ .,
      scales = facet_scale,
      labeller = labeller(sample = facet_labs_y)
    ) +
    scale_fill_manual(values = MBS_COLORS) +
    labs(x = "MBS size", y = "Nr. of MBSs") +
    guides(fill = "none") +
    theme_bw() +
    theme(
      panel.grid.major.x = element_blank(),
      panel.grid.minor.y = element_blank(),
    )
  return(fig)
}
