/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    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: 'copy',
        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
    ]

    withName: 'SAMPLESHEET_CHECK' {
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: 'copy',
            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'
        ]
    }
}

//
// Input Preparation options
//
process {
    withName: 'CAT_FASTQ' {
        publishDir = [
            path: { "${params.outdir}/fastq" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_merged_fastq
        ]
    }
}

//
// Genome Preparation
//
process {
    withName: 'BWA_INDEX' {
        publishDir = [
            path: { "${params.outdir}/genome/index" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

}

//
// Quality Control options
//
if(!params.skip_qc) {
    process {
        withName: 'FASTQC' {
            ext.args = "--quiet"
            publishDir = [
                    path: { "${params.outdir}/reports/fastqc" },
                    mode: 'copy',
                    pattern: "*.{html,zip}"
                ]
        }
    }
}

//
// Trimming options
//
if (!params.skip_trimming) {
    process {
        withName: 'TRIMGALORE' {
            ext.prefix = { "${meta.id}.trimmed" }
            ext.args   = [
                '--fastqc',
                params.trim_nextseq > 0 ? "--nextseq ${params.trim_nextseq}" : ''
            ].join(' ').trim()
            publishDir = [
                [
                    path: { "${params.outdir}/reports/trimgalore_fastqc" },
                    mode: 'copy',
                    pattern: "*.{html,zip}"
                ],
                [
                    path: { "${params.outdir}/trimgalore" },
                    mode: 'copy',
                    pattern: "*.fq.gz",
                    enabled: params.save_trimmed
                ],
                [
                    path: { "${params.outdir}/trimgalore" },
                    mode: 'copy',
                    pattern: "*.txt"
                ]
            ]
        }
    }
}

//
// Alignment options
//
process {
    withName: 'BWA_MEM' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/bwa" },
            enabled: true,
            mode: 'copy',
            pattern: "*.bam"
        ]
    }
    withName: 'SAMTOOLS_INDEX_BAM' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/bwa" },
            enabled: true,
            mode: 'copy',
            pattern: "*.bai"
        ]
    }
    withName: 'SAMTOOLS_SORT_BAM' {
        ext.args = ""
        ext.prefix = { "${meta.id}.sorted" }
        publishDir = [
            path: { "${params.outdir}/bwa" },
            enabled: params.save_sorted_bam,
            mode: 'copy',
            pattern: "*sorted.bam"
        ]
    }
}

process {
    withName: '.*:BAM_STATS_SAMTOOLS_RAW:.*' {
        publishDir = [
            path: { "${params.outdir}/reports/samtools_stats/${meta.id}" },
            enabled: true,
            mode: 'copy'
        ]
    }
}

//
// Picard MarkDuplicates and Filtering options
//
if (!params.skip_markduplicates) {
    process {
        withName: '.*:MARK_DUPLICATES_PICARD:PICARD_MARKDUPLICATES' {
            ext.args   = 'ASSUME_SORTED=true REMOVE_DUPLICATES=false VALIDATION_STRINGENCY=LENIENT TMP_DIR=tmp'
            ext.prefix = { "${meta.id}.md" }
            publishDir = [
                [
                    path: { "${params.outdir}/reports/markduplicates" },
                    mode: 'copy',
                    pattern: '*metrics.txt'
                ],
                [
                    path: { "${params.outdir}/markduplicates/bam" },
                    mode: 'copy',
                    pattern: '*.md.{bam,bai}',
                    enable: params.save_markduplicates_bam
                ]
            ]
        }

        withName: '.*:MARK_DUPLICATES_PICARD:SAMTOOLS_INDEX' {
            ext.prefix = { "${meta.id}.markdup.sorted" }
            publishDir = [
                path: { "${params.outdir}/bwa" },
                mode: 'copy',
                pattern: '*.{bai,csi}'
            ]
        }

        withName: '.*:MARK_DUPLICATES_PICARD:BAM_STATS_SAMTOOLS:.*' {
            publishDir = [
                path: { "${params.outdir}/reports/samtools_stats/${meta.id}/md/" },
                mode: 'copy',
                pattern: '*.{stats,flagstat,idxstats}'
            ]
        }
        withName: 'SAMTOOLS_VIEW_FILTER' {
            if (params.keep_duplicates) {
                ext.args = ''
            } else {
                ext.args = '-F 0x0400'
            }
            ext.prefix = { "${meta.id}.md.filtered" }
            publishDir = [
                path: { "${params.outdir}/markduplicates/duplicates_removed" },
                mode: 'copy',
                pattern: '*filtered.{bai,bam}',
                enabled: false
            ]
        }
        withName: 'SAMTOOLS_SORT_FILTERED' {
            ext.args = ""
            ext.prefix = { "${meta.id}.md.filtered.sorted" }
            publishDir = [
                path: { "${params.outdir}/markduplicates/duplicates_removed" },
                mode: 'copy',
                pattern: '*filtered.sorted.bam',
                enabled: true
            ]
        }

        withName: 'SAMTOOLS_INDEX_FILTERED' {
            ext.args = ""
            ext.prefix = { "${meta.id}.md.filtered.sorted" }
            publishDir = [
                path: { "${params.outdir}/markduplicates/duplicates_removed" },
                mode: 'copy',
                enabled: true,
                pattern: '*filtered.sorted.bai'
            ]
        }

    }
}

if ("circle_finder" in params.circle_identifier.split(",")) {
    process {
        withName: 'BEDTOOLS_SORTEDBAM2BED' {
            ext.args = "-cigar"
        }
        withName: 'BEDTOOLS_SPLITBAM2BED' {
            ext.args = "-cigar"
        }
        withName: 'SAMTOOLS_SORT_QNAME_CF' {
            ext.prefix = { "${meta.id}.qname.sorted" }
            ext.args = "-n"
            publishDir = [
                path: { "${params.outdir}/circlefinder/samtools" },
                mode: 'copy',
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: false
            ]
        }
        withName: 'CIRCLEFINDER' {
            ext.args = ""
            publishDir = [
                path: { "${params.outdir}/circlefinder" },
                mode: 'copy',
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: true
            ]
        }
        withName: 'SAMBLASTER' {
            ext.args = "--ignoreUnmated"
            publishDir = [
                path: { "${params.outdir}/circlefinder/samblaster" },
                mode: 'copy',
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: false
            ]
        }
    }
}

if ("circexplorer2" in params.circle_identifier.split(",")) {
    process {
        withName: 'CIRCEXPLORER2_PARSE' {
            ext.args = "-t BWA"
            publishDir = [
                path: { "${params.outdir}/circexplorer2" },
                mode: 'copy',
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: true
            ]
        }
    }
}

process {
    withName: 'CNVKIT_BATCH' {
        ext.args = "--method wgs"
        publishDir = [
            path: { "${params.outdir}/ampliconarchitect/cnvkit" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: false
        ]
    }
    withName: 'CNVKIT_SEGMENT' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/ampliconarchitect/cnvkit" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
    withName: 'COLLECT_SEEDS' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/ampliconarchitect/cnvkit" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
    withName: 'AMPLIFIED_INTERVALS' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/ampliconarchitect/cnvkit" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
    withName: 'AMPLICONARCHITECT_AMPLICONARCHITECT' {
        time        = '96.h'
        ext.args = ""
        publishDir = [
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconarchitect/sv_view" },
                mode: 'copy',
                pattern: '*.{png,pdf}'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconarchitect/amplicons" },
                mode: 'copy',
                pattern: '*{graph.txt,cycles.txt}'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconarchitect/logs" },
                mode: 'copy',
                pattern: '*logs.txt'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconarchitect/cnseg" },
                mode: 'copy',
                pattern: '*cnseg.txt'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconarchitect/summary" },
                mode: 'copy',
                pattern: '*summary.txt'
            ],

        ]
    }
    withName: 'AMPLICONARCHITECT_AMPLICONCLASSIFIER' {
        ext.args = "--annotate_cycles_file --report_complexity --verbose_classification --plotstyle 'individual'"
        publishDir = [
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*.input'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*.log'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*amplicon_classification_profiles.tsv'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*ecDNA_counts.tsv'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*gene_list.tsv'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}/bed" },
                mode: 'copy',
                pattern: '*.bed'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}/annotated_cycles" },
                mode: 'copy',
                pattern: '*annotated_cycles.txt'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}/radar" },
                mode: 'copy',
                pattern: '*class_radar.{png,pdf}'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*_feature_entropy.tsv'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/${meta.id}" },
                mode: 'copy',
                pattern: '*edge_classification_profiles.tsv'
            ]
        ]
    }
    withName: 'AMPLICONARCHITECT_AMPLICONSIMILARITY' {
        ext.args = ""
        publishDir = [
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/input" },
                mode: 'copy',
                pattern: '*.input'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/log" },
                mode: 'copy',
                pattern: '*.log'
            ],
            [
                path: { "${params.outdir}/ampliconarchitect/ampliconclassifier/similarity" },
                mode: 'copy',
                pattern: '*_similarity_scores.tsv'
            ],
        ]
    }
    withName: 'SUMMARISE_AA' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/ampliconarchitect/summary" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }
}

if ("unicycler" in params.circle_identifier.split(",")) {
    process {
        withName: 'UNICYCLER' {
            time        = '96.h'
            ext.args = "--no_rotate"
            publishDir = [
                path: { "${params.outdir}/unicycler" },
                mode: 'copy',
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: true
            ]
        }
        withName: 'SEQTK_SEQ' {
            ext.args = ""
            publishDir = [
                path: { "${params.outdir}/unicycler" },
                mode: 'copy',
                enabled: false
            ]
        }
        withName: 'GETCIRCULARREADS' {
            ext.args = ""
            publishDir = [
                path: { "${params.outdir}/unicycler/getcircularreads" },
                mode: 'copy',
                pattern: '*.unicycler.circular.fastq.gz',
                enabled: true
            ]
        }
        withName: 'MINIMAP2_ALIGN' {
            ext.args = ""
            publishDir = [
                path: { "${params.outdir}/unicycler/minimap2" },
                mode: 'copy',
                pattern: '*.paf',
                enabled: true
            ]
        }
    }
}

//
// Circle-Map Realign & Repeats
//
process {
    withName: 'SAMTOOLS_SORT_QNAME_CM' {
        ext.prefix = { "${meta.id}.qname.sorted" }
        ext.args = "-n"
        publishDir = [
            path: { "${params.outdir}/circlemap/samtools" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: false
        ]
    }
    withName: 'CIRCLEMAP_READEXTRACTOR' {
        ext.prefix = { "${meta.id}.qname.sorted" }
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/circlemap/readextractor" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
    withName: 'SAMTOOLS_SORT_RE' {
        ext.prefix = { "${meta.id}.circular_read_candidates_sorted" }
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/circlemap/readextractor" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: false
        ]
    }
    withName: 'SAMTOOLS_INDEX_RE' {
        ext.prefix = { "${meta.id}.circular_read_candidates_sorted" }
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/circlemap/readextractor" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: false,
            pattern: '*.{bam,bai}'
        ]
    }
    withName: 'CIRCLEMAP_REALIGN' {
        ext.args = ""
        time = '96.h'
        publishDir = [
            path: { "${params.outdir}/circlemap/realign" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
    withName: 'CIRCLEMAP_REPEATS' {
        ext.args = ""
        publishDir = [
            path: { "${params.outdir}/circlemap/repeats" },
            mode: 'copy',
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: true
        ]
    }
}

if (!params.skip_multiqc) {
    process {
        withName: 'MULTIQC' {
            ext.args   = params.multiqc_title ? "--title \"$params.multiqc_title\"" : ''
            publishDir = [
                path: { [
                    "${params.outdir}/multiqc"
                    ].join('') },
                mode: 'copy',
                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'
        ]
    }

}
