# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False
# 
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
#     try:
#         return subprocess.check_output(["which", cmd]).strip()
#     except subprocess.CalledProcessError:
#         return None
# 
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools
    
    if aligned_x:
        sorted_alignments = sorted(aligned_x, key=operator.itemgetter(2))
        e = enumerate(sorted_alignments[0][0])
        nts = [i for i,c in e if c != "-"]
        return [min(nts), min(nts)+len(x)]

def map_to_precursor_biopython(seqs, names, loci, args):
    """map the sequences using biopython package"""
    precursor = precursor_sequence(loci, args.ref).upper()
    dat = dict()
    for s, n in zip(seqs, names):
        res = _align(str(s), precursor)
        if res:
            dat[n] = res
    logger.debug("mapped in %s: %s out of %s" % (loci, len(dat), len(seqs)))
    return dat


def deprecated_map_to_precursors(seqs, names, loci, out_file, args):
    """map sequences to precursors with bowtie"""
    with make_temp_directory() as temp:
        pre_fasta = os.path.join(temp, "pre.fa")
        seqs_fasta = os.path.join(temp, "seqs.fa")
        out_sam = os.path.join(temp, "out.sam")
        pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
        out_precursor_file = out_file.replace("tsv", "fa")
        seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
        if find_cmd("bowtie2-build"):
            cmd = "bowtie2-build -f {pre_fasta} {temp}/pre"

# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False
# 
# Path: seqcluster/libs/do.py
# def find_cmd(cmd):
#     try:
#         return subprocess.check_output(["which", cmd]).strip()
#     except subprocess.CalledProcessError:
#         return None
# 
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


# Path: seqcluster/libs/read.py
from collections import defaultdict
from seqcluster.libs.sam2bed import makeBED
from seqcluster.libs.do import find_cmd, run
from Bio import pairwise2
from Bio.Seq import Seq
import json, itertools
import tempfile, os, contextlib, shutil
import operator
import logging
import pysam
import pybedtools

    
    if aligned_x:
        sorted_alignments = sorted(aligned_x, key=operator.itemgetter(2))
        e = enumerate(sorted_alignments[0][0])
        nts = [i for i,c in e if c != "-"]
        return [min(nts), min(nts)+len(x)]

def map_to_precursor_biopython(seqs, names, loci, args):
    """map the sequences using biopython package"""
    precursor = precursor_sequence(loci, args.ref).upper()
    dat = dict()
    for s, n in zip(seqs, names):
        res = _align(str(s), precursor)
        if res:
            dat[n] = res
    logger.debug("mapped in %s: %s out of %s" % (loci, len(dat), len(seqs)))
    return dat


def deprecated_map_to_precursors(seqs, names, loci, out_file, args):
    """map sequences to precursors with bowtie"""
    with make_temp_directory() as temp:
        pre_fasta = os.path.join(temp, "pre.fa")
        seqs_fasta = os.path.join(temp, "seqs.fa")
        out_sam = os.path.join(temp, "out.sam")
        pre_fasta = get_loci_fasta(loci, pre_fasta, args.ref)
        out_precursor_file = out_file.replace("tsv", "fa")
        seqs_fasta = get_seqs_fasta(seqs, names, seqs_fasta)
        if find_cmd("bowtie2-build"):
            cmd = "bowtie2-build -f {pre_fasta} {temp}/pre"

            run(cmd.format(**locals()))