# vim: syntax=python tabstop=4 expandtab
# coding: utf-8
rule dist_yara_index_fm_update:
    input:
        "{prefix}.dyara_{meth}_{num_bins}.index_up.log"
    output:
        "{prefix}.distyara_{meth}_{num_bins}.index_up.log",
    params:
        idir="{prefix}_{meth}_{num_bins}/",
    shell:
        "cp {input} {output};"


rule dist_yara_index_fm:
    input:
        "{prefix}.dyara_{meth}_{num_bins}.index.log"
    output:
        "{prefix}.distyara_{meth}_{num_bins}.index.log",
    params:
        idir="{prefix}_{meth}_{num_bins}/",
    shell:
        "cp {input} {output};"

rule dist_yara_map_se:
    input:
        log="{prefix}/{reference}.dyara_{meth}_{num_bins}.index.log",
        rd="{prefix}/{reads}.fastq"
    wildcard_constraints:
        config="[a-zA-Z0-9_]+",
        num_bins="[0-9]+"
    output:
        "{prefix}/{reads}.{reference}.distyara_{config}_{meth}_{num_bins}.bam"
    log:
        "{prefix}/{reads}.{reference}.distyara_{config}_{meth}_{num_bins}.bam.log"
    benchmark:
        "{prefix}/{reads}.{reference}.distyara_{config}_{meth}_{num_bins}.bam.bench"
    params:
        indexer_log="{prefix}/{reference}.distyara_{meth}_{num_bins}.index.log",
        num_threads=config["num_threads"],
        out_dir="{prefix}/{reads}.{reference}.distyara_{config}_{meth}_{num_bins}/",
        num_bins="{num_bins}",
        index_dir="{prefix}/{reference}.dyara_{meth}_{num_bins}.indices/",
        misc=lambda wildcards: config["mappers"]["yara_" + wildcards.config],
        tmp_bam_head="{prefix}/header.head",
    shell:
        "mkdir -p {params.out_dir}; "
        "command time -f 'RES:%e\\t%M\\t%P' "
        "sh -c 'seq 0 $(({params.num_bins}-1)) | xargs -I {{}} "
        "sh -c \" ./bin/yara_mapper {params.misc} --output-file {params.out_dir}{{}}.bam {params.index_dir}{{}} {input.rd} > {params.out_dir}{{}}.log 2>&1 \"; rm -r {params.out_dir}{{}}.bam' > {log} 2>&1 ;"
        # "seq 0 $(({params.num_bins}-1)) | xargs -I {{}} ./bin/samtools view -H {params.out_dir}{{}}.bam | grep @SQ | awk -F\":|\\t\" '{{print $3\"\\t\"$5}}' > {params.tmp_bam_head}; "
        # "seq 0 $(({params.num_bins}-1)) | xargs -I {{}} ./bin/samtools view -@ {params.num_threads} -F 4 {params.out_dir}{{}}.bam | ./bin/samtools view -b -t {params.tmp_bam_head} - > {output} ;"
        # "rm {params.tmp_bam_head}; rm -rf {params.out_dir}"
