#' Generate a transcript-to-gene mapping from a GRangesList
#'
#' Generate a \code{data.frame} mapping transcript IDs to gene IDs, based on
#' a GRangesList object generated by \code{getFeatureRanges}.
#'
#' @param grl \code{GRangesList} object, typically generated by
#'   \code{getFeatureRanges}
#' @param filepath Either \code{NULL} or the path to a file where the
#'   transcript-to-gene mapping will be written
#'
#' @author Charlotte Soneson
#'
#' @export
#'
#' @return Invisibly returns a \code{data.frame} with the transcript-to-gene
#'   mapping.
#'
#' @importFrom S4Vectors mcols
#' @importFrom BiocGenerics unlist subset
#' @importFrom utils write.table
#'
#' @examples
#'   ## Get feature ranges
#'   grl <- getFeatureRanges(
#'     gtf = system.file("extdata/small_example.gtf", package = "eisaR"),
#'     featureType = c("spliced", "intron"),
#'     intronType = "separate",
#'     flankLength = 5L,
#'     joinOverlappingIntrons = FALSE,
#'     verbose = TRUE
#'   )
#'
#'   ## Get transcript-to-gene mapping
#'   t2g <- getTx2Gene(grl = grl)
#'   t2g
#'
getTx2Gene <- function(grl, filepath = NULL) {
    grl <- BiocGenerics::unlist(grl)
    grl <- grl[grl$type == "exon"]
    t2g <- unique(data.frame(
        S4Vectors::mcols(grl)[, c("transcript_id", "gene_id")],
        stringsAsFactors = FALSE
    ))

    if (!is.null(filepath)) {
        utils::write.table(t2g, file = filepath, sep = "\t", quote = FALSE,
                           row.names = FALSE, col.names = FALSE)
    }
    invisible(t2g)
}
