#!/usr/bin/env python
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

import sys
import argparse
import functools
from lib_alu_detect import *
import lib_alu_detect_sam as sam
from cid_parser import cid_parser, remove_seq_from_name
mapping_parser = functools.partial(sam.mapping_parser, cid_parser=cid_parser)

default_min_mqv = 5
default_min_tail_match_len = 5
default_min_tail_insert_size = 15


parser = argparse.ArgumentParser(description='Given SAM mapping, produce fastq entry for unmapped portion of the read. Pairing is irrelevant, as lines are processed independently.')
parser.add_argument('-v', '--verbose', action='append_const', const=1, default=[], dest='verbose')
#parser.add_argument('-l', '--pairing', action='store', default='paired=0', dest='pairing')
parser.add_argument('-q', '--min-mqv', action='store', type=int,
                    default=default_min_mqv, dest='min_mqv')
parser.add_argument('-m', '--min-tail-match-len', action='store', type=int,
                    default=default_min_tail_match_len, dest='min_tail_match_len')
parser.add_argument('input', action='store', nargs='?')
args = parser.parse_args()
set_log_level(len(args.verbose))
#sam.set_pairing('paired=1')

if args.input:
    in_fd = gzopen(args.input)
else:
    in_fd = gzopen('-')

for ms in sam.get_mapping_set_gen(in_fd,
                                  mapping_parser=mapping_parser,
                                  check_pairing=False, check_num_mappings=False):
    note('ms: ' + str(ms), 2)

    for d in ms:
        #seq = d['name'].split(':')[5]
        #qual = ':'.join(d['name'].split(':')[6:])[:len(seq)]
        #d['name'] = (':'.join(d['name'].split(':')[0:5])
        #             + ':'
        #             + ':'.join(d['name'].split(':')[6:])[len(seq) + 1:])
        #seq = d['orig_seq']
        #qual = d['orig_qual']
        seq = d['seq']
        qual = d['qual']
        if d['mapped'] and d['st'] == 1:
            seq = sam.reverse_complement(seq)
            qual = sam.reverse(qual)
        #d['name'] = remove_seq_from_name(d['name'])
        note('seq before trimming:  ' + seq, 2)
        note('qual before trimming: ' + qual, 2)
        if d['mapped'] and d['mqv'] >= args.min_mqv:
            ops = sam.parse_cigar_string(d['cigar'])
            tails = sam.get_tail_insert_size(ops, min_tail_match_len=args.min_tail_match_len)
            if tails[0] > 0:
                tails[0] = min(tails[0] + 10, d['len'])
            if tails[1] > 0:
                tails[1] = min(tails[1] + 10, d['len'])
            if d['st'] == 1:
                tails = tails[::-1]
            note('tails: ' + str(tails), 2)
            if tails[0] > 0 and tails[1] == 0:
                seq = seq[:tails[0]]
                qual = qual[:tails[0]]
            elif tails[0] == 0 and tails[1] > 0:
                seq = seq[-tails[1]:]
                qual = qual[-tails[1]:]
            elif tails[0] == 0 and tails[1] == 0:
                seq = ''
                qual = ''
            note('seq after trimming: ' + seq, 2)
        print '\n'.join(['@' + d['name'], seq, '+', qual])

gzclose(in_fd)
