# Path: bipy/utils.py
# def flatten(l):
#     for el in l:
#         if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
#             for sub in flatten(el):
#                 yield sub
#         else:
#             yield el
# 
# def remove_suffix(filename):
#     filename, extension = os.path.splitext(filename)
#     return filename
# 
# def is_pair(arg):
#     """
#     check if 'arg' is a two-item sequence
# 
#     """
#     return is_sequence(arg) and len(arg) == 2
# 
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
#     """Abstract class for generating Latex reports. Inherit from this
#     and implement template and generate_report"""
#     __metaclass__ = abc.ABCMeta
# 
#     @abc.abstractproperty
#     def template(self):
#         return
# 
#     @abc.abstractmethod
#     def generate_report(self, *args, **kwargs):
#         """Generate the Latex output using the template"""
#         return
# 
# def safe_latex(to_fix):
#     """Escape characters that make LaTeX unhappy.
#     Lifted from Brad Chapman (bcbio)
#     """
#     chars = ["%", "_", "&", "#"]
#     for char in chars:
#         to_fix = to_fix.replace(char, "\\%s" % char)
#     return to_fix
# 
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
#     """
#     Wrapper around a stage for use with the pipeline manager. Subclasses should
#     implement their own __init__ in addition to calling the super
#     __init__. __init__ should parse the appropriate information from the config
#     dict and save it in the objects state. __call__ should be implemented as a
#     pure function with no closures.
# 
#     """
# 
#     stage = "abstract"
# 
#     def __init__(self, config):
#         self.config = config
#         self._validate_config()
# 
#     def _start_message(self, in_file, **kwargs):
#         if kwargs:
#             logger.info("Starting %s on %s with arguments %s." % (self.stage,
#                                                                   in_file,
#                                                                   kwargs))
#         else:
#             logger.info("Starting %s on %s." % (self.stage, in_file))
# 
#     def _end_message(self, in_file):
#         logger.info("%s complete on %s." % (self.stage, in_file))
# 
#     def _check_run(self, in_file):
#         if not file_exists(in_file):
#             raise IOError("%s not found." % (in_file))
# 
#     def __call__(self, in_file):
#         pass
# 
#     def _validate_config(self):
#         if "stage" not in self.config:
#             raise ValueError('Could not find "stage" in the config file.')


import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do
                "Per sequence quality scores",
                "Per base sequence content",
                "Per base GC content",
                "Per sequence GC content",
                "Per base N content",
                "Sequence Length Distribution",
                "Overrepresented sequences"]


def _make_outdir(config):
    """ make the output directory "fastqc" where the data files live """
    outdir = os.path.join(config["dir"]["results"], "fastqc")
    safe_makedir(outdir)
    return outdir


def _make_outfile(input_file, config):
    outdir = _make_outdir(config)
    #outfile = "".join([os.path.basename(input_file), "_fastqc.zip"])
    base, ext = os.path.splitext(os.path.basename(input_file))
    # fastqc does not handle the .fq extension correctly
    if ext == ".fq":
        outfile = os.path.join(outdir, base + ext + "_fastqc.zip")
    else:
        outfile = os.path.join(outdir, base + "_fastqc.zip")
    return outfile


def _build_command(input_file, fastqc_config, config):
    program = fastqc_config["program"]

# Path: bipy/utils.py
# def flatten(l):
#     for el in l:
#         if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
#             for sub in flatten(el):
#                 yield sub
#         else:
#             yield el
# 
# def remove_suffix(filename):
#     filename, extension = os.path.splitext(filename)
#     return filename
# 
# def is_pair(arg):
#     """
#     check if 'arg' is a two-item sequence
# 
#     """
#     return is_sequence(arg) and len(arg) == 2
# 
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
#     """Abstract class for generating Latex reports. Inherit from this
#     and implement template and generate_report"""
#     __metaclass__ = abc.ABCMeta
# 
#     @abc.abstractproperty
#     def template(self):
#         return
# 
#     @abc.abstractmethod
#     def generate_report(self, *args, **kwargs):
#         """Generate the Latex output using the template"""
#         return
# 
# def safe_latex(to_fix):
#     """Escape characters that make LaTeX unhappy.
#     Lifted from Brad Chapman (bcbio)
#     """
#     chars = ["%", "_", "&", "#"]
#     for char in chars:
#         to_fix = to_fix.replace(char, "\\%s" % char)
#     return to_fix
# 
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
#     """
#     Wrapper around a stage for use with the pipeline manager. Subclasses should
#     implement their own __init__ in addition to calling the super
#     __init__. __init__ should parse the appropriate information from the config
#     dict and save it in the objects state. __call__ should be implemented as a
#     pure function with no closures.
# 
#     """
# 
#     stage = "abstract"
# 
#     def __init__(self, config):
#         self.config = config
#         self._validate_config()
# 
#     def _start_message(self, in_file, **kwargs):
#         if kwargs:
#             logger.info("Starting %s on %s with arguments %s." % (self.stage,
#                                                                   in_file,
#                                                                   kwargs))
#         else:
#             logger.info("Starting %s on %s." % (self.stage, in_file))
# 
#     def _end_message(self, in_file):
#         logger.info("%s complete on %s." % (self.stage, in_file))
# 
#     def _check_run(self, in_file):
#         if not file_exists(in_file):
#             raise IOError("%s not found." % (in_file))
# 
#     def __call__(self, in_file):
#         pass
# 
#     def _validate_config(self):
#         if "stage" not in self.config:
#             raise ValueError('Could not find "stage" in the config file.')


# Path: bipy/toolbox/fastqc.py
import subprocess
import os
import logging
import abc
import sh
import zipfile
from bipy.utils import flatten, remove_suffix, is_pair
from bcbio.utils import safe_makedir, file_exists
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bipy.pipeline.stages import AbstractStage
from bcbio.log import logger, setup_local_logging
from bcbio.provenance import do

                "Per sequence quality scores",
                "Per base sequence content",
                "Per base GC content",
                "Per sequence GC content",
                "Per base N content",
                "Sequence Length Distribution",
                "Overrepresented sequences"]


def _make_outdir(config):
    """ make the output directory "fastqc" where the data files live """
    outdir = os.path.join(config["dir"]["results"], "fastqc")
    safe_makedir(outdir)
    return outdir


def _make_outfile(input_file, config):
    outdir = _make_outdir(config)
    #outfile = "".join([os.path.basename(input_file), "_fastqc.zip"])
    base, ext = os.path.splitext(os.path.basename(input_file))
    # fastqc does not handle the .fq extension correctly
    if ext == ".fq":
        outfile = os.path.join(outdir, base + ext + "_fastqc.zip")
    else:
        outfile = os.path.join(outdir, base + "_fastqc.zip")
    return outfile


def _build_command(input_file, fastqc_config, config):
    program = fastqc_config["program"]

    options = map(str, list(flatten(fastqc_config["options"])))