
rule bwa_bam_to_fastq:
    """Converts mapped BAM into fastq

    Required output:
        - __bwa_bam_to_fastq__input: into BAM file

    Required output:
        - __bwa_bam_to_fastq__fastq_output: the FastQ files
        - __bwa_bam_to_fastq__stats_output: a JSON file to store some stats

    Required parameters:
        - __bwa_bam_to_fastq__wkdir: where to save the files

    Notes: FastQ are gzipped

    :References: Sequana function StatsBAM2Mapped
    """
    message: """
    -- Extracting the fastq from the BAM/SAM files
    -- information saved in {log}
    """
    input:
        bam = __bwa_bam_to_fastq__input
    output:
        fastq = __bwa_bam_to_fastq__fastq_output,
        stats = __bwa_bam_to_fastq__stats_output
    params:
        wkdir = __bwa_bam_to_fastq__wkdir
    threads: 4
    run:
        # save some stats for later
        from sequana.tools import StatsBAM2Mapped
        stats = StatsBAM2Mapped(input["bam"], wkdir=params.wkdir)
        stats.to_json(output["stats"])

        # zip the fastq files
        import glob
        for filename in glob.glob("%s/*.fastq" % params.wkdir):
            shell("pigz -f %s -p {threads}" % filename)



