# Path: AGEpy/gtf.py
# def GTFtoBED(inGTF,name):
#     """
#     Transform a GTF dataframe into a bed dataframe
# 
#     :param inGTF: GTF dataframe for transformation
#     :param name: field of the GTF data frame to be use for the bed 'name' positon
# 
#     returns: a bed dataframe with the corresponding bed fiels: 'chrom','chromStart','chromEnd','name','score','strand'
#     """
# 
#     bed=inGTF.copy()
#     bed.reset_index(inplace=True, drop=True)
#     if name not in bed.columns.tolist():
#         field=retrieve_GTF_field(name, bed)
#         bed=pd.concat([bed,field],axis=1)
#     bed=bed[['seqname','start','end',name,'score','strand']]
#     bed.columns=['chrom','chromStart','chromEnd','name','score','strand']
#     bed.drop_duplicates(inplace=True)
#     bed.reset_index(inplace=True,drop=True)
#     return bed
# 
# Path: AGEpy/gtf.py
# def readGTF(infile):
#     """
#     Reads a GTF file and labels the respective columns in agreement with GTF file standards:
#     'seqname','source','feature','start','end','score','strand','frame','attribute'.
# 
#     :param infile: path/to/file.gtf
#     :returns: a Pandas dataframe of the respective GTF
# 
#     """
#     df=pd.read_table(infile, sep='\t', comment="#", header=None, dtype=str)
#     df.columns=['seqname','source','feature','start','end','score','strand','frame','attribute']
#     #df = df.astype(str) # from DTC
#     return df
# 
# Path: AGEpy/gtf.py
# def retrieve_GTF_field(field,gtf):
#     """
#     Returns a field of choice from the attribute column of the GTF
# 
#     :param field: field to be retrieved
#     :returns: a Pandas dataframe with one columns containing the field of choice
# 
#     """
#     inGTF=gtf.copy()
#     def splits(x):
#         l=x.split(";")
#         l=[ s.split(" ") for s in l]
#         res=np.nan
#         for s in l:
#             if field in s:
#                 if '"' in s[-1]:
#                     res=s[-1][1:-1]
#                 else:
#                     res=s[-1]
#         return res
# 
#     inGTF[field]=inGTF['attribute'].apply(lambda x: splits(x))
#     return inGTF[[field]]


import pandas as pd
import numpy as np
import os
import urllib.request as urllib2
import gzip
import pybedtools
import sys
from io import StringIO
from pybedtools import BedTool
from .gtf import GTFtoBED
from .gtf import readGTF
from .gtf import retrieve_GTF_field
        df=pd.merge(df,tmp,on=field,how="left")

        return df

    dfTargets=getCounts_GeneIDs(dfTargets)


    dfTargets=dfTargets.drop(["count"],axis=1)
    return dfTargets

def AnnotateBED(bed, GTF, genome_file, bedcols=None, promoter=[1000,200]):
    """
    Annotates a bed file.

    :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols.
    :param GTF: /path/to/file.gtf
    :param genome_file: /path/to/file.genome - a tab separated values of chr name and size information
    :param bedcols: a comma separated string of column headers to use when reading in a bed file. eg: "chr,start,end,name"
    :param promoter: a list containing the upstream start of the promoter region from the TSS and the downstream end of the promoter region from the TSS.

    :returns: a Pandas dataframe with the annotated bed file. exons and promoters will be reported as well in the annotated_gene_features column.
    """
    if type(bed) == type("string"):
        bed=pd.read_table(bed,header=None)
        bed.columns=bedcols.split(",")

    print("Reading GTF file.")
    sys.stdout.flush()

    GTF=readGTF(GTF)

# Path: AGEpy/gtf.py
# def GTFtoBED(inGTF,name):
#     """
#     Transform a GTF dataframe into a bed dataframe
# 
#     :param inGTF: GTF dataframe for transformation
#     :param name: field of the GTF data frame to be use for the bed 'name' positon
# 
#     returns: a bed dataframe with the corresponding bed fiels: 'chrom','chromStart','chromEnd','name','score','strand'
#     """
# 
#     bed=inGTF.copy()
#     bed.reset_index(inplace=True, drop=True)
#     if name not in bed.columns.tolist():
#         field=retrieve_GTF_field(name, bed)
#         bed=pd.concat([bed,field],axis=1)
#     bed=bed[['seqname','start','end',name,'score','strand']]
#     bed.columns=['chrom','chromStart','chromEnd','name','score','strand']
#     bed.drop_duplicates(inplace=True)
#     bed.reset_index(inplace=True,drop=True)
#     return bed
# 
# Path: AGEpy/gtf.py
# def readGTF(infile):
#     """
#     Reads a GTF file and labels the respective columns in agreement with GTF file standards:
#     'seqname','source','feature','start','end','score','strand','frame','attribute'.
# 
#     :param infile: path/to/file.gtf
#     :returns: a Pandas dataframe of the respective GTF
# 
#     """
#     df=pd.read_table(infile, sep='\t', comment="#", header=None, dtype=str)
#     df.columns=['seqname','source','feature','start','end','score','strand','frame','attribute']
#     #df = df.astype(str) # from DTC
#     return df
# 
# Path: AGEpy/gtf.py
# def retrieve_GTF_field(field,gtf):
#     """
#     Returns a field of choice from the attribute column of the GTF
# 
#     :param field: field to be retrieved
#     :returns: a Pandas dataframe with one columns containing the field of choice
# 
#     """
#     inGTF=gtf.copy()
#     def splits(x):
#         l=x.split(";")
#         l=[ s.split(" ") for s in l]
#         res=np.nan
#         for s in l:
#             if field in s:
#                 if '"' in s[-1]:
#                     res=s[-1][1:-1]
#                 else:
#                     res=s[-1]
#         return res
# 
#     inGTF[field]=inGTF['attribute'].apply(lambda x: splits(x))
#     return inGTF[[field]]


# Path: AGEpy/bed.py
import pandas as pd
import numpy as np
import os
import urllib.request as urllib2
import gzip
import pybedtools
import sys
from io import StringIO
from pybedtools import BedTool
from .gtf import GTFtoBED
from .gtf import readGTF
from .gtf import retrieve_GTF_field

        df=pd.merge(df,tmp,on=field,how="left")

        return df

    dfTargets=getCounts_GeneIDs(dfTargets)


    dfTargets=dfTargets.drop(["count"],axis=1)
    return dfTargets

def AnnotateBED(bed, GTF, genome_file, bedcols=None, promoter=[1000,200]):
    """
    Annotates a bed file.

    :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols.
    :param GTF: /path/to/file.gtf
    :param genome_file: /path/to/file.genome - a tab separated values of chr name and size information
    :param bedcols: a comma separated string of column headers to use when reading in a bed file. eg: "chr,start,end,name"
    :param promoter: a list containing the upstream start of the promoter region from the TSS and the downstream end of the promoter region from the TSS.

    :returns: a Pandas dataframe with the annotated bed file. exons and promoters will be reported as well in the annotated_gene_features column.
    """
    if type(bed) == type("string"):
        bed=pd.read_table(bed,header=None)
        bed.columns=bedcols.split(",")

    print("Reading GTF file.")
    sys.stdout.flush()

    GTF=readGTF(GTF)

    GTF["gene_name"]=retrieve_GTF_field("gene_name", GTF)