# Path: crumbs/utils/test_utils.py
# TEST_DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
#                                              '..', 'test', 'test_data'))
# 
# Path: crumbs/utils/bin_utils.py
# BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..',
#                                        'bin'))
# 
# Path: crumbs/bam/bam_tools.py
# def filter_bam(in_fpath, out_fpath, min_mapq=0, required_flag_tags=None,
#                filtering_flag_tags=None, regions=None):
#     cmd = ['-bh']
# 
#     # The following line:
#     cmd.append('-o' + out_fpath)
#     # should be
#     # cmd.extend(['-o', out_fpath])
#     # but it is a workaround, take a look at:
#     # https://groups.google.com/forum/#!msg/pysam-user-group/ooHgIiNVe4c/CcY06d45rzQJ
# 
#     if min_mapq:
#         cmd.extend(['-q', str(min_mapq)])
# 
#     if required_flag_tags:
#         flag = create_flag(required_flag_tags)
#         cmd.extend(['-f', str(flag)])
# 
#     if filtering_flag_tags:
#         flag = create_flag(filtering_flag_tags)
#         cmd.extend(['-F', str(flag)])
# 
#     cmd.extend([in_fpath])
# 
#     if regions:
#         regions = ['{0}:{1}-{2}'.format(*s) for s in regions.segments]
#         cmd.extend(regions)
# 
#     pysam.view(*cmd)
# 
# def calmd_bam(in_bam_fpath, reference_fpath, out_bam_fpath=None):
# 
#     if out_bam_fpath is None:
#         out_bam_fpath = in_bam_fpath
# 
#     if out_bam_fpath == in_bam_fpath:
#         realigned_fhand = NamedTemporaryFile(suffix='.realigned.bam',
#                                              delete=False)
#         temp_out_fpath = realigned_fhand.name
#     else:
#         temp_out_fpath = out_bam_fpath
# 
#     _calmd_bam(in_bam_fpath, reference_fpath, temp_out_fpath)
# 
#     if temp_out_fpath != out_bam_fpath:
#         shutil.move(temp_out_fpath, out_bam_fpath)
# 
# def realign_bam(in_bam_fpath, reference_fpath, out_bam_fpath=None):
# 
#     if out_bam_fpath is None:
#         out_bam_fpath = in_bam_fpath
# 
#     if out_bam_fpath == in_bam_fpath:
#         realigned_fhand = NamedTemporaryFile(suffix='.realigned.bam',
#                                              delete=False)
#         temp_out_fpath = realigned_fhand.name
#     else:
#         temp_out_fpath = out_bam_fpath
# 
#     _realign_bam(in_bam_fpath, reference_fpath, temp_out_fpath, threads=False)
#     sort_bam(temp_out_fpath)
# 
#     if temp_out_fpath != out_bam_fpath:
#         shutil.move(temp_out_fpath, out_bam_fpath)
# 
# def index_bam(bam_fpath):
#     'It indexes a bam file'
#     pysam.index(bam_fpath)
# 
# def merge_sams(in_fpaths, out_fpath):
#     picard_jar = get_setting("PICARD_JAR")
# 
#     cmd = ['java', '-jar', picard_jar, 'MergeSamFiles',
#            'O={}'.format(out_fpath)]
#     for in_fpath in in_fpaths:
#         cmd.append('I={}'.format(in_fpath))
#     stderr = NamedTemporaryFile(suffix='picard.stderr')
#     stdout = NamedTemporaryFile(suffix='picard.stdout')
#     try:
#         check_call(cmd, stderr=stderr, stdout=stdout)
#     except CalledProcessError:
#         sys.stderr.write(open(stderr.name).read())
#         sys.stdout.write(open(stdout.name).read())


import os.path
import unittest
import shutil
import pysam
from subprocess import check_output, check_call
from tempfile import NamedTemporaryFile
from crumbs.utils.test_utils import TEST_DATA_DIR
from crumbs.utils.bin_utils import BIN_DIR
from crumbs.bam.bam_tools import (filter_bam, calmd_bam, realign_bam,
                                  index_bam, merge_sams)
        index_bam(bam_fpath)

    def test_merge_sam(self):
        bam_fpath = os.path.join(TEST_DATA_DIR, 'sample.bam')
        fhand = NamedTemporaryFile(suffix='.bam')
        out_fpath = fhand.name
        fhand.close()
        try:
            merge_sams([bam_fpath, bam_fpath], out_fpath=out_fpath)
            samfile = pysam.Samfile(out_fpath)
            assert len(list(samfile)) == 2
            assert os.stat(bam_fpath) != os.stat(out_fpath)
        finally:
            if os.path.exists(out_fpath):
                os.remove(out_fpath)


class FilterTest(unittest.TestCase):
    def test_filter_mapq(self):
        bam_fpath = os.path.join(TEST_DATA_DIR, 'seqs.bam')
        out_fhand = NamedTemporaryFile()
        filter_bam(bam_fpath, out_fhand.name, min_mapq=100)
        assert len(open(out_fhand.name).read(20)) == 20


class RealignTest(unittest.TestCase):
    def test_realign_bamself(self):
        ref_fpath = os.path.join(TEST_DATA_DIR, 'CUUC00007_TC01.fasta')
        bam_fpath = os.path.join(TEST_DATA_DIR, 'sample.bam')
        out_bam = NamedTemporaryFile()

# Path: crumbs/utils/test_utils.py
# TEST_DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
#                                              '..', 'test', 'test_data'))
# 
# Path: crumbs/utils/bin_utils.py
# BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..',
#                                        'bin'))
# 
# Path: crumbs/bam/bam_tools.py
# def filter_bam(in_fpath, out_fpath, min_mapq=0, required_flag_tags=None,
#                filtering_flag_tags=None, regions=None):
#     cmd = ['-bh']
# 
#     # The following line:
#     cmd.append('-o' + out_fpath)
#     # should be
#     # cmd.extend(['-o', out_fpath])
#     # but it is a workaround, take a look at:
#     # https://groups.google.com/forum/#!msg/pysam-user-group/ooHgIiNVe4c/CcY06d45rzQJ
# 
#     if min_mapq:
#         cmd.extend(['-q', str(min_mapq)])
# 
#     if required_flag_tags:
#         flag = create_flag(required_flag_tags)
#         cmd.extend(['-f', str(flag)])
# 
#     if filtering_flag_tags:
#         flag = create_flag(filtering_flag_tags)
#         cmd.extend(['-F', str(flag)])
# 
#     cmd.extend([in_fpath])
# 
#     if regions:
#         regions = ['{0}:{1}-{2}'.format(*s) for s in regions.segments]
#         cmd.extend(regions)
# 
#     pysam.view(*cmd)
# 
# def calmd_bam(in_bam_fpath, reference_fpath, out_bam_fpath=None):
# 
#     if out_bam_fpath is None:
#         out_bam_fpath = in_bam_fpath
# 
#     if out_bam_fpath == in_bam_fpath:
#         realigned_fhand = NamedTemporaryFile(suffix='.realigned.bam',
#                                              delete=False)
#         temp_out_fpath = realigned_fhand.name
#     else:
#         temp_out_fpath = out_bam_fpath
# 
#     _calmd_bam(in_bam_fpath, reference_fpath, temp_out_fpath)
# 
#     if temp_out_fpath != out_bam_fpath:
#         shutil.move(temp_out_fpath, out_bam_fpath)
# 
# def realign_bam(in_bam_fpath, reference_fpath, out_bam_fpath=None):
# 
#     if out_bam_fpath is None:
#         out_bam_fpath = in_bam_fpath
# 
#     if out_bam_fpath == in_bam_fpath:
#         realigned_fhand = NamedTemporaryFile(suffix='.realigned.bam',
#                                              delete=False)
#         temp_out_fpath = realigned_fhand.name
#     else:
#         temp_out_fpath = out_bam_fpath
# 
#     _realign_bam(in_bam_fpath, reference_fpath, temp_out_fpath, threads=False)
#     sort_bam(temp_out_fpath)
# 
#     if temp_out_fpath != out_bam_fpath:
#         shutil.move(temp_out_fpath, out_bam_fpath)
# 
# def index_bam(bam_fpath):
#     'It indexes a bam file'
#     pysam.index(bam_fpath)
# 
# def merge_sams(in_fpaths, out_fpath):
#     picard_jar = get_setting("PICARD_JAR")
# 
#     cmd = ['java', '-jar', picard_jar, 'MergeSamFiles',
#            'O={}'.format(out_fpath)]
#     for in_fpath in in_fpaths:
#         cmd.append('I={}'.format(in_fpath))
#     stderr = NamedTemporaryFile(suffix='picard.stderr')
#     stdout = NamedTemporaryFile(suffix='picard.stdout')
#     try:
#         check_call(cmd, stderr=stderr, stdout=stdout)
#     except CalledProcessError:
#         sys.stderr.write(open(stderr.name).read())
#         sys.stdout.write(open(stdout.name).read())


# Path: test/bam/test_bam_tools.py
import os.path
import unittest
import shutil
import pysam
from subprocess import check_output, check_call
from tempfile import NamedTemporaryFile
from crumbs.utils.test_utils import TEST_DATA_DIR
from crumbs.utils.bin_utils import BIN_DIR
from crumbs.bam.bam_tools import (filter_bam, calmd_bam, realign_bam,
                                  index_bam, merge_sams)

        index_bam(bam_fpath)

    def test_merge_sam(self):
        bam_fpath = os.path.join(TEST_DATA_DIR, 'sample.bam')
        fhand = NamedTemporaryFile(suffix='.bam')
        out_fpath = fhand.name
        fhand.close()
        try:
            merge_sams([bam_fpath, bam_fpath], out_fpath=out_fpath)
            samfile = pysam.Samfile(out_fpath)
            assert len(list(samfile)) == 2
            assert os.stat(bam_fpath) != os.stat(out_fpath)
        finally:
            if os.path.exists(out_fpath):
                os.remove(out_fpath)


class FilterTest(unittest.TestCase):
    def test_filter_mapq(self):
        bam_fpath = os.path.join(TEST_DATA_DIR, 'seqs.bam')
        out_fhand = NamedTemporaryFile()
        filter_bam(bam_fpath, out_fhand.name, min_mapq=100)
        assert len(open(out_fhand.name).read(20)) == 20


class RealignTest(unittest.TestCase):
    def test_realign_bamself(self):
        ref_fpath = os.path.join(TEST_DATA_DIR, 'CUUC00007_TC01.fasta')
        bam_fpath = os.path.join(TEST_DATA_DIR, 'sample.bam')
        out_bam = NamedTemporaryFile()

        realign_bam(bam_fpath, ref_fpath, out_bam.name)