from os import listdir
from os.path import isfile, basename, splitext

rule all:
    input:
        expand("premapping/fastqc/{SAMPLE}_R{DIRECTION}_fastqc.html", SAMPLE=config['entries'].keys(), DIRECTION=[1,2]),
        ".report/modules/fastqc.html"

rule fastqc:
    input:
        "preprocessing/{sample}.fastq.gz"
    output:
        "premapping/fastqc/{sample}_fastqc.html",
        "premapping/fastqc/{sample}_fastqc.zip"
    conda:
        "../lib/conda_env.yaml"
    group:
        "fastqc"
    threads:
        1
    shell:
        "fastqc -o premapping/fastqc {input}"


rule groups_file:
    input:
        html=expand("premapping/fastqc/{SAMPLE}_R{DIRECTION}_fastqc.html", SAMPLE=config['entries'].keys(), DIRECTION=[1,2])
    output:
        groups=temp("premapping/fastqc/groups.tsv")
    run:
        with open(output.groups, 'w') as out:
            out.write("Sample\tFprward\tReverse\n")
            for entry in config['entries'].keys():
                out.write("{}\t{}_R1_fastqc.html\t{}_R2_fastqc.html\n".format(entry, entry, entry))


rule generate_report:
    input:
        reports_list="premapping/fastqc/groups.tsv",
        reports=expand("premapping/fastqc/{SAMPLE}_R{DIRECTION}_fastqc.html", SAMPLE=config['entries'].keys(), DIRECTION=[1,2])
    output:
        fastqc_data=".report/data/fastqc_data.js",
        fastqc_html=".report/modules/fastqc.html",
        fastqc_js=".report/js/modules/fastqc.js",
        fastqc_reports=directory(".report/modules/fastqc/")
    conda:
        "../lib/conda_env.yaml"
    group:
        "fastqc_report"
    shell:
        "mkdir -p {output.fastqc_reports} && cp {input.reports} {output.fastqc_reports} && "
        "python3 lib/generate_report_data.py --reports {input.reports_list} --output {output.fastqc_data} --paired-end && "
        "cp lib/report/fastqc.html {output.fastqc_html} && "
        "cp lib/report/fastqc.js {output.fastqc_js}"
