


# should be called after bwa_mem and bwa_bam


def fastqc_dynamic(name, manager):
    metadata = {'name':name, "project":manager.sample}
    fastqc_code = '''

rule fastqc_%(name)s:
    """Calls FastQC on input data sets (paired or not)

    This rule is a **dynamic** rule (see developers guide). It can be included
    in a pipeline with different names. For instance in the quality_control
    pipeline, it is used as fastqc_samples and fastqc_phix. Here below,
    the string %(name)s must be replaced by the appropriate dynamic name.

    Required input:
        - __fastqc_%(name)s__input_fastq:

    Required output:
        - __fastqc_%(name)s__output_done

    Required parameters
        - __fastqc_%(name)s__wkdir: the working directory

    Log:
        - logs/fastqc_%(name)s/fastqc.log

    Required configuration:
        .. code-block:: yaml

            fastqc:
                options: "-nogroup"   # a string with fastqc options

    References:
        - http://www.bioinformatics.babraham.ac.uk/projects/fastqc/
    """
    # we could have a dynamic search or based on config file
    input:
        fastq = __fastqc_%(name)s__input_fastq
    output:
        touch(__fastqc_%(name)s__output_done)
    params:
        wkdir = __fastqc_%(name)s__wkdir,
        kargs = config['fastqc']['options']
    threads: 4
    log:
        fastqc = "logs/fastqc_%(name)s/fastqc.log",
    run:
        # if the content of the file is empty, this will fail. We need to
        # touch  a file in such case.
        from sequana import snaketools as sm
        from sequana import FastQ
        newinput = []
        for i, this in enumerate(input.fastq):
            fastq = FastQ(this)
            # TODO: could just try to iterate once instead of computing the length
            if len(fastq) != 0:
                newinput.append(this)
            else:
                pass

        if len(newinput):
            shell(
            " fastqc -t {threads} --outdir {params.wkdir} -f fastq "
            " {newinput} {params.kargs} > {log.fastqc}")
        else:
            pass
    '''
    from sequana.snaketools import build_dynamic_rule
    return build_dynamic_rule(fastqc_code % metadata, manager.pipeline_dir)
