

def fastq_stats_dynamic(name, manager):

    metadata = {'name':name}

    fastq_stats_code = '''
rule fastq_stats_%(name)s:
    """Analyse FastQ files to extract basic stats

    Creates boxplot quality image + GC content + basic stats in JSON file

    Required input:
       - __fastq_stats_%(name)s__input_fastq:

    Required output:
       - __fastq_stats_%(name)s__output_done

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

    This rule creates files that are not in the required output namely
    a *_gc.png* *_boxplot.png_* and *.json* files with filename set to the
    original FastQ filename.

    Note: analyses only first 500,000 reads

    """
    input:
        fastq = __fastq_stats_%(name)s__input_fastq
    output:
        done    = touch(__fastq_stats_%(name)s__output_done)
    params:
        wkdir = __fastq_stats_%(name)s__wkdir,
    threads: 4
    run:
        from sequana import FastQC, sequana_data
        import pylab
        pylab.ioff()

        ff = sm.FileFactory(input.fastq)

        for i, filename in enumerate(ff.realpaths):
            # The ouput files
            formatter = lambda x: params.wkdir + "/" + x.replace(".fastq.gz","")
            output_gc = formatter(ff.basenames[i] + "_gc.png")
            output_boxplot = formatter(ff.basenames[i] + "_boxplot.png")
            output_json = formatter(ff.basenames[i] + ".json")

            fastq = FastQC(filename, max_sample=500000)
            if len(fastq.fastq) != 0:
                pylab.clf()
                fastq.boxplot_quality()
                pylab.savefig(output_boxplot)

                pylab.clf()
                fastq.histogram_gc_content()
                pylab.savefig(output_gc)

                stats = fastq.get_stats()
                stats.to_json(output_json)
            else:
                import shutil
                from easydev import touch
                location = sequana_data("no_data.jpg", "images")
                shutil.copy(location, output_gc)
                shutil.copy(location, output_boxplot)
                # this will be handled inside report_fastq_stats
                touch(output_json)

    '''
    from sequana.snaketools import build_dynamic_rule
    return build_dynamic_rule(fastq_stats_code % metadata, manager.pipeline_dir)
