#!/usr/bin/env python2.7
# parseFunctionalElements
"""Parse out the functional elements from a gff3 file."""
import os
import sys
import argparse
import urllib

funcElems = ["CAAT_signal","GC_rich_promoter_region","TATA_box","enhancer","insulator",
"locus_control_region","mobile_genetic_element","origin_of_replication","promoter",
"protein_binding_site","recombination_feature","regulatory_region","repeat_region",
"sequence_feature","sequence_secondary_structure","silencer","stem_loop"]

def parseArgs(args):
	"""
	Parse the command line arguments.
	"""
	parser= argparse.ArgumentParser(description= __doc__)
	parser.add_argument ("inputFile",
		help = " The input file. ",
		type = argparse.FileType("r"))
	parser.add_argument ("outputFile",
		help = " The output file. ",
		type =argparse.FileType("w"))
	parser.add_argument ("annotationVersion",
		help = " The annotation version. ex 108.20170627",
        action = "store")

	if (len(sys.argv) == 1):
		parser.print_help()
		exit(1)
	options = parser.parse_args()
	return options

def main(args):
    """
    Initialized options and calls other functions.
    """
    options = parseArgs(args)
    seenDescriptions = []
    firstItem = True
    for line in options.inputFile:
        if line.startswith("#"):
            continue
        splitLine = line.strip("\n").split("\t")
        if len(splitLine) is not 10:
            print ("This is not the proper input file format.")
            exit(1)
        if splitLine[2] not in funcElems: 
            continue
        chrom = splitLine[9]
        seqId = splitLine[0]
        source = splitLine[1]
        soTerm = splitLine[2]
        chrStart = str(int(splitLine[3]) -1)
        chrEnd = splitLine[4]
        
        if (int(chrEnd) - int(chrStart)) > 10000000:
            print ("This item was longer than 10,000,000 bp and was excluded " + str(int(chrEnd) - int(chrStart)) + " " + chrom)
            continue
        
        if (".") in splitLine[5]:
            score = '0'
        else:
            score = splitLine[5]
        strand = splitLine[6]
        phase = splitLine[7]
        attributes = ""
        soTermBlock = [urllib.unquote(x).decode('utf8').split("=") for x in splitLine[8].split(";")]
        temp = []
        sID = ""
        gbkey = ""
        note = ""
        experiment = ""
        function = ""
        regulatory_class = ""
        standard_name = ""
        pubMedIds = ""
        mouseOver = ""
        for item in soTermBlock:
            if "ID" in item[0]:
                sID = item[1]
            elif "Note" in item[0]:
                note = item[1]
                mouseOver = note
            elif "experiment" in item[0]:
                experiment = item[1]
                if "PMID" in item[1]:
                    pmids = item[1].split("[")
                    for item in pmids:
                        if "PMID" in item:
                            for pub in item.strip("]").split(","): 
                                pubMedIds += (pub.split(":")[1]) + ","
            elif "function" in item[0]:
                function = item[1]
                mouseOver += " | " + function
            elif "standard_name" in item[0]:
                standard_name = item[1]
            elif "Dbxref" in item[0]:
                dbXref = item[1].split(",")
                for item2 in dbXref: 
                    if "GeneID" in item2:
                        geneId = item2.split(":")[1]
            else:
                attributes += item[0] + "=" + item[1] + "; "
        options.outputFile.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" %
                (chrom, chrStart, chrEnd, geneId, score, strand, \
                    soTerm, note, pubMedIds.strip(","), experiment, \
                    function, options.annotationVersion, mouseOver))
    

if __name__ == "__main__" : 
    sys.exit(main(sys.argv))
