#!/usr/bin/env python
from __future__ import print_function
# Programmer : zhuxp
# Date: 
# Last-modified: 05-13-2014, 13:10:38 EDT
VERSION="0.1.0"
import os,sys,argparse
from bam2x.Annotation import BED6 as Bed
from bam2x.Annotation import BED12 as Bed12
from bam2x import TableIO,Tools,IO
from bam2x import DBI
import time
import logging
import itertools
def help():
    return "cmp region with gene set(bed12 format) "
def set_parser(p):
    ''' This Function Parse the Argument '''
    p.add_argument('-g','--gene',dest="genetab",type=str,help="Gene File, BED12 Format ")
    p.add_argument('-s','--strand',dest="strand",type=str,choices=("read1","read2"),default="read2",help="strand read1 or read2 , default: %(default)s")
    p.add_argument('-u','--upstream',dest="upstream",type=int,default=3000,help="upstream bp number , default: 3000")
    p.add_argument('-d','--downstream',dest="downstream",type=int,default=3000,help="downstream bp number , default: 3000")
    
def run(local_args):
    '''
    IO TEMPLATE
    '''
    logging.basicConfig(level=logging.INFO);
    global args,out
    args=local_args
    out=IO.fopen(args.output,"w")
    fin=IO.fopen(args.input,"r")
    print("# This data was generated by program ",sys.argv[0]," (version: %s)"%VERSION,file=out)
    print("in bam2x ( https://github.com/nimezhu/bam2x )",file=out)
    print("# Date: ",time.asctime(),file=out)
    print("# The command line is :",file=out)
    print("#\t"," ".join(sys.argv),file=out)
    gene=DBI.init(args.genetab,"binindex",cls="bed12");
    upstream_list=[]
    downstream_list=[]
    exons_list=[]
    introns_list=[]
    utr3_list=[]
    utr5_list=[]
    for g in gene:
        upstream_list.append(g.upstream(args.upstream));
        downstream_list.append(g.downstream(args.downstream));
        for e in g.Exons():
            exons_list.append(e)
        for i in g.Introns():
            introns_list.append(i)
        if not (g.utr3() is None):
            utr3_list.append(g.utr3())
        if not (g.utr5() is None):
            utr5_list.append(g.utr5())
    upstream=DBI.init(upstream_list,"binindex",cls="bed6")
    downstream=DBI.init(downstream_list,"binindex",cls="bed6")
    exons=DBI.init(exons_list,"binindex",cls="bed6")
    introns=DBI.init(introns_list,"binindex",cls="bed6")
    utr3=DBI.init(utr3_list,"binindex",cls="bed6")
    utr5=DBI.init(utr5_list,"binindex",cls="bed6")
    dbs=[upstream,gene,utr5,exons,introns,utr3,downstream]
    db_names=["upstream","gene","utr5","exons","introns","utr3","downstream"]
    db_rep=["U","G","5","E","I","3","D"]
    h={}
    def report(f,total):
        print( "# "+" ".join(["{rep}:{name} ".format(name=i,rep=j) for i,j in itertools.izip(db_names,db_rep)]),file=out);
        print("# total reads: {total:.0f}".format(total=total),file=out);
        for i0 in sorted(h.keys()):
            print("{key}\t{value:.0f}\t{fraction:.2f}%".format(key=i0,value=h[i0],fraction=float(h[i0])*100/total),file=f);
    s=0.0;
    for i,x in enumerate(TableIO.parse(fin,"bam2bed12",strand=args.strand)):
        pattern=["_" for j in range(7)];
        if i%10000==0:
            logging.info("processed {number} reads".format(number=i));
            report(sys.stderr,s);
        for j,db in enumerate(dbs):
            if hit(db.query(x)):
                pattern[j]=db_rep[j]
        pattern_bytes="".join(pattern); 
        NH=int(x.itemRgb.split(",")[0])
        if NH==0: NH=1;
        nh=1.0/NH
        s+=nh
        if h.has_key(pattern_bytes):
            h[pattern_bytes]+=nh
        else:
            h[pattern_bytes]=nh
    report(out,s)
    



def hit(x):
    for i in x:
        return True
    return False



if __name__=="__main__":
    from bam2x.IO import parser_factory
    p=parser_factory(description=help())
    set_parser(p)
    if len(sys.argv)==1:
        print(p.print_help())
        exit(0)
    run(p.parse_args())

    





