/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Config file for defining DSL2 per module options and publishing paths
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Available keys to override module options:
        ext.args   = Additional arguments appended to command in module.
        ext.args2  = Second set of arguments appended to command in module (multi-tool modules).
        ext.args3  = Third set of arguments appended to command in module (multi-tool modules).
        ext.prefix = File name prefix for output files.
----------------------------------------------------------------------------------------
*/

process {

    publishDir = [
        path: { "${params.outdir}/${task.process.tokenize(':')[-1].tokenize('_')[0].toLowerCase()}" },
        mode: params.publish_dir_mode,
        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
    ]

    withName: SAMPLESHEET_CHECK {
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }

    withName: CUSTOM_DUMPSOFTWAREVERSIONS {
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: params.publish_dir_mode,
            pattern: '*_versions.yml'
        ]
    }

    withName: FASTQC {
        ext.args = '--quiet'
        publishDir = [
            [
                path: { "${params.outdir}/fastqc" },
                mode: params.publish_dir_mode,
                pattern: "*.html"
            ],
            [
                path: { "${params.outdir}/fastqc/zips" },
                mode: params.publish_dir_mode,
                pattern: "*.zip"
            ]
        ]
    }

    withName: TRIMGALORE {
        ext.args = { [
            // Static args
            '--fastqc',

            // Special flags
            params.rrbs ? '--rrbs' : '',
            params.nextseq_trim > 0 ? "--nextseq ${params.nextseq_trim}" : '',

            // Trimming - R1
            params.clip_r1 > 0 ? "--clip_r1 ${params.clip_r1}" : (
                params.pbat ? "--clip_r1 9" : (
                    (params.single_cell || params.cegx) ? "--clip_r1 6" : (
                        params.epignome ? "--clip_r1 8" : (
                            (params.accel || params.zymo || params.em_seq) ? "--clip_r1 10" : ''
                        )
                    )
                )
            ),

            // Trimming - R2
            meta.single_end ? '' : (
                params.clip_r2 > 0 ? "--clip_r2 ${params.clip_r2}" : (
                    params.pbat ? "--clip_r2 9" : (
                        (params.single_cell || params.cegx) ? "--clip_r2 6" : (
                            params.epignome ? "--clip_r2 8" : (
                                (params.zymo || params.em_seq) ? "--clip_r2 10" : (
                                    params.accel ? "--clip_r2 15" : ''
                                )
                            )
                        )
                    )
                )
            ),

            // Trimming - 3' R1
            params.three_prime_clip_r1 > 0 ? "--three_prime_clip_r1 ${params.three_prime_clip_r1}" : (
                params.pbat ? "--three_prime_clip_r1 9" : (
                    params.single_cell ? "--three_prime_clip_r1 6" : (
                        params.cegx ? "--three_prime_clip_r1 2" : (
                            params.epignome ? "--three_prime_clip_r1 8" : (
                                (params.accel || params.zymo || params.em_seq) ? "--three_prime_clip_r1 10" : ''
                            )
                        )
                    )
                )
            ),

            // Trimming - 3' R2
            meta.single_end ? '' : (
                params.three_prime_clip_r2 > 0 ? "--three_prime_clip_r2 ${params.three_prime_clip_r2}" : (
                    params.pbat ? "--three_prime_clip_r2 9" : (
                        params.single_cell ? "--three_prime_clip_r2 6" : (
                            params.cegx ? "--three_prime_clip_r2 2" : (
                                params.epignome ? "--three_prime_clip_r2 8" : (
                                    (params.accel || params.zymo || params.em_seq) ? "--three_prime_clip_r2 10" : ''
                                )
                            )
                        )
                    )
                )
            ),
        ].join(' ').trim() }
        publishDir = [
            [
                path: { "${params.outdir}/trimgalore/fastqc" },
                mode: params.publish_dir_mode,
                pattern: "*.html"
            ],
            [
                path: { "${params.outdir}/trimgalore/fastqc/zips" },
                mode: params.publish_dir_mode,
                pattern: "*.zip"
            ],
            [
                path: { "${params.outdir}/trimgalore" },
                mode: params.publish_dir_mode,
                pattern: "*.fq.gz",
                enabled: params.save_trimmed
            ],
            [
                path: { "${params.outdir}/trimgalore/logs" },
                mode: params.publish_dir_mode,
                pattern: "*.txt"
            ]
        ]
    }

    withName: BISMARK_GENOMEPREPARATION {
        ext.args = [
            params.aligner == 'bismark_hisat' ? ' --hisat2' : ' --bowtie2',
            params.slamseq ? ' --slam' : ''
        ].join(' ').trim()
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/reference_genome" },
            saveAs: { it =~ /.*\.yml/ ? null : it },
            mode: params.publish_dir_mode,
            enabled: params.save_reference
        ]
    }

    withName: BISMARK_ALIGN {
        ext.args = { [
            params.aligner == 'bismark_hisat' ? ' --hisat2' : ' --bowtie2',
            params.aligner == 'bismark_hisat' && params.known_splices ? " --known-splicesite-infile <(hisat2_extract_splice_sites.py ${known_splices})" : '',
            params.pbat ? ' --pbat' : '',
            ( params.single_cell || params.non_directional || params.zymo ) ? ' --non_directional' : '',
            params.unmapped ? ' --unmapped' : '',
            params.relax_mismatches ? " --score_min L,0,-${params.num_mismatches}" : '',
            params.local_alignment ? " --local" : '',
            !meta.single_end && params.minins ? " --minins ${params.minins}" : '',
            meta.single_end ? '' : (
                params.maxins ? " --maxins ${params.maxins}" : (
                    params.em_seq ? " --maxins 1000" : ''
                )
            )
        ].join(' ').trim() }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/alignments/unmapped" },
                mode: params.publish_dir_mode,
                pattern: "*.fq.gz",
                enabled: params.unmapped
            ],
            [
                path: { "${params.outdir}/${params.aligner}/alignments" },
                mode: params.publish_dir_mode,
                pattern: "*.bam",
                enabled: (params.save_align_intermeds || params.skip_deduplication || params.rrbs)
            ],
            [
                path: { "${params.outdir}/${params.aligner}/alignments/logs" },
                mode: params.publish_dir_mode,
                pattern: "*.txt"
            ]
        ]
    }

    withName: BISMARK_DEDUPLICATE {
        ext.args = ''
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated/logs" },
                mode: params.publish_dir_mode,
                pattern: "*.txt"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated" },
                mode: params.publish_dir_mode,
                pattern: "*.bam"
            ]
        ]
    }

    withName: BISMARK_METHYLATIONEXTRACTOR {
        ext.args = { [
            params.comprehensive   ? ' --comprehensive --merge_non_CpG' : '',
            params.meth_cutoff     ? " --cutoff ${params.meth_cutoff}" : '',
            params.nomeseq         ? '--CX' : '',
            params.ignore_r1 > 0   ? '--ignore ${params.ignore_r1}' : '',
            params.ignore_3prime_r1 > 0   ? '--ignore_3prime ${params.ignore_3prime_r1}' : '',
            meta.single_end ? '' : (params.no_overlap           ? ' --no_overlap'                         : '--include_overlap'),
            meta.single_end ? '' : (params.ignore_r2        > 0 ? "--ignore_r2 ${params.ignore_r2}"       : ""),
            meta.single_end ? '' : (params.ignore_3prime_r2 > 0 ? "--ignore_3prime_r2 ${params.ignore_3prime_r2}": "")
        ].join(' ').trim() }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/methylation_calls/mbias" },
                mode: params.publish_dir_mode,
                pattern: "*M-bias.txt"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/methylation_calls/methylation_coverage" },
                mode: params.publish_dir_mode,
                pattern: "*cov.gz"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/methylation_calls/bedGraph" },
                mode: params.publish_dir_mode,
                pattern: "*bedGraph.gz"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/methylation_calls/splitting_report" },
                mode: params.publish_dir_mode,
                pattern: "*splitting_report.txt"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/methylation_calls/methylation_calls" },
                mode: params.publish_dir_mode,
                pattern: "*txt.gz"
            ]
        ]
    }

    withName: BISMARK_COVERAGE2CYTOSINE {
        ext.args = params.nomeseq ? '--nome-seq' : ''
        publishDir = [
            publishDir = [
                path: { "${params.outdir}/bismark/coverage2cytosine/summaries" },
                mode: params.publish_dir_mode,
                pattern: "*_summary.txt"
            ],
            publishDir = [
                path: { "${params.outdir}/bismark/coverage2cytosine/reports" },
                mode: params.publish_dir_mode,
                pattern: "*_report.txt.gz"
            ],
            publishDir = [
                path: { "${params.outdir}/bismark/coverage2cytosine/coverage" },
                mode: params.publish_dir_mode,
                pattern: "*cov.gz"
            ]
        ]
    }

    withName: BISMARK_REPORT {
        ext.args = ''
        publishDir = [
            path: "${params.outdir}/${params.aligner}/reports",
            mode: params.publish_dir_mode,
            pattern: "*.html"
        ]
    }


    withName: BISMARK_SUMMARY {
        ext.args = ''
        publishDir = [
            path: "${params.outdir}/${params.aligner}/summary",
            mode: params.publish_dir_mode,
            pattern: "*.{html,txt}"
        ]
    }

    withName: BWAMETH_INDEX {
        ext.args = ''
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/reference_genome" },
            mode: params.publish_dir_mode,
            saveAs: { it.equals('versions.yml') ? null : it.tokenize("/").last() },
            enabled: params.save_reference
        ]
    }

    withName: BWAMETH_ALIGN {
        ext.args = ''
        publishDir = [
                path: { "${params.outdir}/${params.aligner}/alignments" },
                pattern: "*.bam",
                mode: params.publish_dir_mode,
                enabled: params.save_align_intermeds
        ]
    }

    withName: PICARD_MARKDUPLICATES {
        ext.args = "--ASSUME_SORTED true --REMOVE_DUPLICATES false --VALIDATION_STRINGENCY LENIENT --PROGRAM_RECORD_ID 'null' --TMP_DIR tmp"
        ext.prefix = { "${meta.id}.markdup.sorted" }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated/picard_metrics" },
                pattern: "*.metrics.txt",
                mode: params.publish_dir_mode
            ],
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated" },
                pattern: "*.bam",
                mode: params.publish_dir_mode
            ]
        ]
    }

    withName: SAMTOOLS_SORT {
        ext.prefix = { "${meta.id}.sorted" }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated/" },
                mode: params.publish_dir_mode,
                pattern: "*markdup*.bam",
                enabled: params.save_align_intermeds
            ],
            [
                path: { "${params.outdir}/${params.aligner}/alignments/" },
                mode: params.publish_dir_mode,
                pattern: "*.bam",
                enabled: params.save_align_intermeds
            ]
        ]
    }

    withName: SAMTOOLS_FLAGSTAT {
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/alignments/samtools_stats/" },
                mode: params.publish_dir_mode,
                pattern: "*.flagstat"
            ]
        ]
    }

    withName: SAMTOOLS_STATS {
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/alignments/samtools_stats/" },
                mode: params.publish_dir_mode,
                pattern: "*.stats"
            ]
        ]
    }

    withName: SAMTOOLS_FAIDX {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/reference_genome" },
            mode: params.publish_dir_mode,
            enabled: params.save_reference,
            pattern: "*.fai"
        ]
    }

    withName: SAMTOOLS_INDEX_ALIGNMENTS {
        ext.args = ""
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/alignments/" },
                mode: params.publish_dir_mode,
                pattern: "*.bam*",
                enabled: params.save_align_intermeds
            ]
        ]
    }

    withName: SAMTOOLS_INDEX_DEDUPLICATED {
        ext.args = ""
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/deduplicated/" },
                mode: params.publish_dir_mode,
                pattern: "*.bai"
            ]
        ]
    }

    withName: METHYLDACKEL_MBIAS {
        ext.args = [
            params.comprehensive ? ' --CHG --CHH' : '',
            params.ignore_flags ? " --ignoreFlags" : ''
        ].join(" ").trim()
        publishDir = [
            [
                path: { "${params.outdir}/methyldackel/mbias" },
                mode: params.publish_dir_mode,
                pattern: "*mbias.txt"
            ]
        ]
    }

    withName: METHYLDACKEL_EXTRACT {
        ext.args = [
            params.comprehensive ? ' --CHG --CHH' : '',
            params.ignore_flags ? " --ignoreFlags" : '',
            params.methyl_kit ? " --methylKit" : '',
            params.min_depth > 0 ? " --minDepth ${params.min_depth}" : ''
        ].join(" ").trim()
        publishDir = [
            [
                path: { "${params.outdir}/methyldackel" },
                mode: params.publish_dir_mode,
                pattern: "*.bedGraph"
            ]
        ]
    }

    withName: QUALIMAP_BAMQC {
        ext.args = [
            params.genome.toString().startsWith('GRCh') ? '-gd HUMAN' : '',
            params.genome.toString().startsWith('GRCm') ? '-gd MOUSE' : ''
        ].join(" ").trim()
    }

    withName: PRESEQ_LCEXTRAP {
        ext.args = " -verbose -bam"
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/preseq" },
                mode: params.publish_dir_mode,
                pattern: "*.txt"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/preseq/log" },
                mode: params.publish_dir_mode,
                pattern: "*.log"
            ]
        ]
    }

    withName: 'MULTIQC' {
        ext.args   = params.multiqc_title ? "--title \"$params.multiqc_title\"" : ''
        publishDir = [
            path: { "${params.outdir}/multiqc/${params.aligner}" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }

}






