# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
#     cur_dir =  os.getcwd()
#     os.chdir(p)
#     try:
#         yield
#     finally:
#         os.chdir(cur_dir)
# 
# def safe_dirs(dirs):
#     if not os.path.exists(dirs):
#         os.makedirs(dirs)
#     return dirs
# 
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
# 
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
#     def note(self, message, *args, **kws):
#     NOTE = 15
#     COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
#     COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
#     DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
#     FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
#     FORMAT_INFO = "%(levelname)s %(message)s"
# 
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
#     """get fasta from precursor"""
#     if not find_cmd("bedtools"):
#         raise ValueError("Not bedtools installed")
#     with make_temp_directory() as temp:
#         bed_file = os.path.join(temp, "file.bed")
#         for nc, loci in loci.iteritems():
#             for l in loci:
#                 with open(bed_file, 'w') as bed_handle:
#                     logger.debug("get_fasta: loci %s" % l)
#                     nc, c, s, e, st = l
#                     print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
#                 get_fasta(bed_file, ref, out_fa)
#     return out_fa
# 
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
#     temp_dir = tempfile.mkdtemp()
#     yield temp_dir
#     shutil.rmtree(temp_dir)
# 
# Path: seqcluster/libs/do.py
# 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/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):


from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil
"""Implementation of open source tools to predict small RNA functions"""


# import seqcluster.libs.logger as mylog

logger = mylog.getLogger(__name__)


def run_coral(clus_obj, out_dir, args):
    """
    Run some CoRaL modules to predict small RNA function
    """
    if not args.bed:
        raise ValueError("This module needs the bed file output from cluster subcmd.")
    workdir = op.abspath(op.join(args.out, 'coral'))
    safe_dirs(workdir)
    bam_in = op.abspath(args.bam)
    bed_in = op.abspath(args.bed)
    reference = op.abspath(args.ref)
    with chdir(workdir):
        bam_clean = coral.prepare_bam(bam_in, bed_in)
        out_dir = op.join(workdir, "regions")
        safe_dirs(out_dir)
        prefix = "seqcluster"
        loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)

# Path: seqcluster/libs/utils.py
# @contextlib.contextmanager
# def chdir(p):
#     cur_dir =  os.getcwd()
#     os.chdir(p)
#     try:
#         yield
#     finally:
#         os.chdir(cur_dir)
# 
# def safe_dirs(dirs):
#     if not os.path.exists(dirs):
#         os.makedirs(dirs)
#     return dirs
# 
# Path: seqcluster/libs/utils.py
# def chdir(p):
# def safe_dirs(dirs):
# def safe_remove(fn):
# def safe_run(fn):
# def file_exists(fname):
# 
# Path: seqcluster/libs/logger.py
# def getLogger(name):
# def set_format(frmt, frmt_col=None, datefmt=None):
# def initialize_logger(output_dir, debug, level=False):
#     def note(self, message, *args, **kws):
#     NOTE = 15
#     COLOR_FORMAT = "%(log_color)s%(asctime)s%(levelname)s-%(name)s(%(lineno)d)%(reset)s: %(message)s"
#     COLOR_FORMAT_INFO = "%(log_color)s%(asctime)s %(levelname)s%(reset)s: %(message)s"
#     DATE_FRT = '%m/%d/%Y %I:%M:%S %p'
#     FORMAT = "%(levelname)s-%(name)s(%(lineno)d): %(message)s"
#     FORMAT_INFO = "%(levelname)s %(message)s"
# 
# Path: seqcluster/libs/read.py
# def get_loci_fasta(loci, out_fa, ref):
#     """get fasta from precursor"""
#     if not find_cmd("bedtools"):
#         raise ValueError("Not bedtools installed")
#     with make_temp_directory() as temp:
#         bed_file = os.path.join(temp, "file.bed")
#         for nc, loci in loci.iteritems():
#             for l in loci:
#                 with open(bed_file, 'w') as bed_handle:
#                     logger.debug("get_fasta: loci %s" % l)
#                     nc, c, s, e, st = l
#                     print("{0}\t{1}\t{2}\t{3}\t{3}\t{4}".format(c, s, e, nc, st), file=bed_handle)
#                 get_fasta(bed_file, ref, out_fa)
#     return out_fa
# 
# @contextlib.contextmanager
# def make_temp_directory(remove=True):
#     temp_dir = tempfile.mkdtemp()
#     yield temp_dir
#     shutil.rmtree(temp_dir)
# 
# Path: seqcluster/libs/do.py
# 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/function/coral.py
# def prepare_bam(bam_in, precursors):
# def _select_anno(annotation):
# def _reorder_columns(bed_file):
# def _fix_score_column(cov_file):
# def detect_regions(bam_in, bed_file, out_dir, prefix):
# def _order_antisense_column(cov_file, min_reads):
# def _reads_per_position(bam_in, loci_file, out_dir):
# def create_features(bam_in, loci_file, reference, out_dir):
# def prepare_ann_file(args):
# def download_hsa_file(args):


# Path: seqcluster/function/predictions.py
from os import path as op
from seqcluster.libs.utils import chdir, safe_dirs
from seqcluster.libs import utils, logger as mylog
from seqcluster.libs.read import get_loci_fasta, make_temp_directory
from seqcluster.libs.do import run
from seqcluster.function import coral
import os
import shutil

"""Implementation of open source tools to predict small RNA functions"""


# import seqcluster.libs.logger as mylog

logger = mylog.getLogger(__name__)


def run_coral(clus_obj, out_dir, args):
    """
    Run some CoRaL modules to predict small RNA function
    """
    if not args.bed:
        raise ValueError("This module needs the bed file output from cluster subcmd.")
    workdir = op.abspath(op.join(args.out, 'coral'))
    safe_dirs(workdir)
    bam_in = op.abspath(args.bam)
    bed_in = op.abspath(args.bed)
    reference = op.abspath(args.ref)
    with chdir(workdir):
        bam_clean = coral.prepare_bam(bam_in, bed_in)
        out_dir = op.join(workdir, "regions")
        safe_dirs(out_dir)
        prefix = "seqcluster"
        loci_file = coral.detect_regions(bam_clean, bed_in, out_dir, prefix)

        coral.create_features(bam_clean, loci_file, reference, out_dir)