import operator


def transcript_exons_to_bed12(exons_list, transcript_id):
    """
    Convert a list of exon Genomic Intervals from a transcripts (from HTseq) to bed12 line
    """

    blockSizes = []
    blockStarts = []
    sorted_exons = sorted(exons_list, key=operator.attrgetter("iv.start"))
    chrom = sorted_exons[0].iv.chrom
    tr_start = min(sorted_exons[0].iv.start, sorted_exons[0].iv.end, sorted_exons[-1].iv.start, sorted_exons[-1].iv.end)
    tr_end = max(sorted_exons[0].iv.start, sorted_exons[0].iv.end, sorted_exons[-1].iv.start, sorted_exons[-1].iv.end)
    strand = sorted_exons[0].iv.strand
    items = len(sorted_exons)
    
    for exon in sorted_exons:
        blockStarts.append(str(exon.iv.start - tr_start))
        blockSizes.append(str(exon.iv.end - exon.iv.start))
    
    bed12_entry = "\t".join([
        chrom,
        str(tr_start),
        str(tr_end),
        transcript_id,
        "1",
        strand,
        str(tr_start),
        str(tr_end),
        "0",
        str(items),
        ",".join(blockSizes)+",",
        ",".join(blockStarts)+",",
        ])
    
    return bed12_entry