import argparse
from copy import deepcopy
from JunctionAnnotator import Junction
import os
import pysam
import sys

class AnnotatedJunction(Junction):
    """ Subclass of Class Junction"""
    def __init__(self, line):
        sline = line.rstrip().split
        chrom = sline[0]
        strand = sline[5]
        start = sline[1]
        suepr(AnnotatedJunction, self).__init__(chrom,strand,start)
        start = self.thick_start + int(sline[10].split(',')[0])
        self.thick_start = int(sline[1])
        self.thick_end = int(sline[2])
        self.name = sline[3]
        self.read_count = int(sline[4])
        self.score = sline[4]
        self.end = self.thick_start + int(sline[11].split(',')[1])
        self.left_anchor = True
        self.right_anchor = True
        self.donor_seq = ""
        self.acceptor_seq = ""
        self.known_junc = False
        self.known_donor = False
        self.known_acceptor = False
    
    def get_splice_site(self, fasta):
        donor_pos = [self.start + 1, self.start + 2]
        acceptor_pos = [self.end -2, self.end - 1]
        donor_seq = fasta.fetch(self.chrom, donor_pos[0], donor_pos[1]).upper()
        acceptor_seq = fasta.fetch(self.chrom, acceptor_pos[0], acceptor_pos[1]).upper()
        if self.strand == '-':
            base_dict = {
                'A': 'T',
                'C': 'G',
                'G': 'C',
                'T': 'A',
                'N': 'N'
            }
            donor_seq = [base_dict[i] for i in donor_seq]
            donor_seq = donor_seq[::-1]
            acceptor_seq = [base_dict[i] for i in acceptor_seq]
            acceptor_seq = acceptor_seq[::-1]
            donor_pos, acceptor_seq = acceptor_seq, donor_seq
        self.donor_seq = donor_seq
        self.acceptor_seq = acceptor_seq

def parse_opt():
    parser = argparse.ArgumentParser(description='Extract Junction Reads from bamfile')
    parser.add_argument('-a', '--anchor', type=int, default=8, help='mininum anchor length')
    parser.add_argument('-f', '--fastq', help='reference genome fasta file', required=True)
    parser.add_argument('-j', '--junc', help='input junction file generated by JunctExtractor', required=True)
    parser.add_argument('-g', '--gtf', help='tabix gtf file as annotation')
    parser.add_argument('-o', '--out', help='output file path')
    parser.add_argument('-r', '--region', help='junction reads from spcific regions')
    args = parser.parse_args()
    return args

def get_fasta_file(fastafile):
    try:
        fasta = pysam.FastaFile(fastafile)
    except IOError:
        msg='%s not found!' % fastafile
        print(msg)
    except AttributeError:
        msg='index of %s not found' % fastafile
    else:
        return fasta

def get_annotation(gtffile):
    try:
        gtf = pysam.Tabixfile(gtffile)
        return gtf
    except IOError:
        msg='%s not found!' % gtffile
        print(msg)

def overlap_annotation(junc, anno):
    ts_set = anno.fetch(junc.chrom, junc.start, junc.end, parser=pysam.asGTF())
    exon_set = filter(lambda x: x.feature=='exon', [i for i in ts_set])
    for idx,exon in enumerate(exon_set):
        if idx == len(exon_set) - 1:
            continue
        

    for(std::size_t i = 0; i < exons.size(); i++) {
        if(exons[i].start > junction.end) {
            //No need to look any further
            //the rest of the exons are outside the junction
            break;
        }
        //known junction
        if(exons[i].end == junction.start &&
                exons[i + 1].start == junction.end) {
            junction.known_acceptor = true;
            junction.known_donor = true;
            junction.known_junction = true;
            known_junction = true;
        }
        else {
            if(!junction_start) {
                if(exons[i].end >= junction.start) {
                    junction_start = true;
                }
            }
            if(junction_start) {
                if(exons[i].start > junction.start &&
                        exons[i].end < junction.end) {
                    junction.exons_skipped.insert(exons[i].name);
                }
                if(exons[i].start > junction.start) {
                    junction.donors_skipped.insert(exons[i].start);
                }
                if(exons[i].end < junction.end) {
                    junction.acceptors_skipped.insert(exons[i].end);
                }
                if(exons[i].end == junction.start) {
                    junction.known_donor = true;
                }
                //TODO - check for last exon
                if(exons[i].start == junction.end) {
                    junction.known_acceptor = true;
                }
            }
        }
    }
    annotate_anchor(junction);
    return (junction.anchor != "N");
}

    pass

def annotate_junction(juncfile, anno, fasta):
    try:
        with open(juncfile) as junc:
            for line in junc:
                junc = Junction.init_from_file(line)
                junc.get_splice_site(fasta)
    except:
        msg='%s not found!' % juncfile
        print(msg)

if __name__ == '__main__':
    args = parse_opt()
    fasta = get_fasta_file(args.fasta)
    anno = get_annotation(args.gtf)
    annotate_junction(args.junc, anno, fasta)


