import collections
try:
    from utils import revCompIterative
    from utils import sortORFs
except ImportError:
    from ORForise.utils import revCompIterative
    from ORForise.utils import sortORFs


def GFF(*args):
    tool_pred = args[0]
    dna_regions = args[1]
    if not dna_regions: # This triggers if dna_regions is an empty dict (GFF_Intersect passed nothing)
        dna_regions = collections.OrderedDict()
        with open(tool_pred, 'r') as GFF_input:
            for line in GFF_input:
                line = line.split()
                if 'CDS' in line[2] and len(line) == 9 and line[0] not in dna_regions:
                    dna_regions[line[0]] = []  # Placeholder for genome sequence
        return dna_regions

    GFF_ORFs = collections.OrderedDict()
    for dna_region in dna_regions:
        GFF_ORFs[dna_region] = collections.OrderedDict()
    for dna_region in dna_regions:
        try:
            genome = dna_regions[dna_region][0]
        except IndexError:
            genome = dna_regions[dna_region]
        genome_size = len(genome)
        genome_rev = revCompIterative(genome)
        with open(tool_pred, 'r') as gff_input:
            for line in gff_input:
                if not line.startswith('#'):
                    line = line.split('\t')
                    #gene_types = types.split(',') - Temporary fix
                    #if any(gene_type == line[2] for gene_type in gene_types) and len(line) == 9:  # line[2] for normalrun
                    if 'CDS' in line[2] and len(line) == 9 and dna_region in line[0]:
                        start = int(line[3])
                        stop = int(line[4])
                        strand = line[6]
                        info = line[8]
                        if stop >= genome_size:
                            extra_stop = stop - genome_size
                            corrected_stop = genome_size
                            if '-' in strand:  # Reverse Compliment starts and stops adjusted
                                r_start = genome_size - corrected_stop
                                r_stop = genome_size - start
                                seq = genome_rev[r_start:r_stop + 1]
                                extra_seq = genome_rev[-extra_stop - 1:]
                                seq = extra_seq+seq
                                startCodon = seq[:3]
                                stopCodon = seq[-3:]
                            elif '+' in strand:
                                seq = genome[start -1 :corrected_stop]
                                extra_seq = genome[:extra_stop +1]
                                seq = seq+extra_seq
                                startCodon = seq[:3]
                                stopCodon = seq[-3:]
                        else:
                            if '-' in strand:  # Reverse Compliment starts and stops adjusted
                                r_start = genome_size - stop
                                r_stop = genome_size - start
                                startCodon = genome_rev[r_start:r_start + 3]
                                stopCodon = genome_rev[r_stop - 2:r_stop + 1]
                            elif '+' in strand:
                                startCodon = genome[start - 1:start + 2]
                                stopCodon = genome[stop - 3:stop]
                        po = str(start) + ',' + str(stop)
                        orf = [strand, startCodon, stopCodon, line[2], 'GFF-Standard'] # This needs to detect the type
                        GFF_ORFs[dna_region].update({po: orf})
                    # elif "CDS" in line[2]:
                    #     sys.exit("SAS")

    for group in GFF_ORFs:
        GFF_ORFs[group] = sortORFs(GFF_ORFs[group])
    return GFF_ORFs
