/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    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: CUSTOM_DUMPSOFTWAREVERSIONS {
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: params.publish_dir_mode,
            pattern: '*_versions.yml'
        ]
    }

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

    withName: 'MOLKARTQC' {
        publishDir = [
            path: { "${params.outdir}/molkartqc" },
            pattern: "*.csv"
        ]
    }

    withName: 'MOLKARTQCPNG' {
        ext.when = { params.create_training_subset }
        publishDir = [
            path: { "${params.outdir}/molkartqc" },
            pattern: "*.png"
        ]
    }

    withName: 'CREATE_STACK' {
        ext.when  = { image.size() > 1 }
        ext.prefix = { "${meta.id}_stack" }
        ext.args  = [ "",
            params.clahe_pyramid_tile ? "--tile_size ${params.clahe_pyramid_tile}" : "",
            params.clahe_pixel_size   ? "--pixel_size ${params.clahe_pixel_size}"  : ""
        ].join(" ").trim()
        publishDir = [
            path: { "${params.outdir}/stack" },
            mode: params.publish_dir_mode,
            pattern: "*.{ome.tif}"
        ]
    }

    withName: "MASKFILTER" {
        ext.prefix = { "${meta.id}_${meta.segmentation}_filtered" }
        ext.args = [ "",
            params.segmentation_min_area ? "--min_area ${params.segmentation_min_area}" : "",
            params.segmentation_max_area ? "--max_area ${params.segmentation_max_area}" : ""
        ].join(" ").trim()
        publishDir = [
            path: { "${params.outdir}/segmentation/filtered_masks" },
            mode: params.publish_dir_mode,
            pattern: "*.{tiff,tif}"
        ]
    }

    withName: "MINDAGAP_MINDAGAP" {
        ext.args = [ "",
            params.mindagap_boxsize ? "${params.mindagap_boxsize}" : "",
            params.mindagap_loopnum ? "${params.mindagap_loopnum}" : "",
            params.mindagap_tilesize ? "-xt ${params.mindagap_tilesize}" : ""
        ].join(" ").trim()
        publishDir = [
            path: { "${params.outdir}/mindagap" },
            pattern: "*.{tiff,tif}",
            saveAs: { filename -> "${meta.id}_$filename" }
        ]
    }

    withName: "MINDAGAP_DUPLICATEFINDER" {
        ext.args = [ "",
            params.mindagap_tilesize ? "${params.mindagap_tilesize}" : ""
        ].join(" ").trim()
        publishDir = [
            path: { "${params.outdir}/mindagap" },
            pattern: "*.{tsv,txt}",
            mode: params.publish_dir_mode,
            saveAs: { filename -> "${meta.id}_$filename" }
        ]
    }

    withName: "SPOT2CELL" {
        ext.prefix = { "${meta.id}_${meta.segmentation}"}
        publishDir = [
            path: { "${params.outdir}/spot2cell" },
            pattern: "*.csv",
            mode: params.publish_dir_mode,
            saveAs: { filename -> "cellxgene_$filename" }
        ]
    }

    withName: "ILASTIK_PIXELCLASSIFICATION" {
        ext.when = { params.segmentation_method.split(',').contains('ilastik') }
        publishDir = [
            path: { "${params.outdir}/segmentation/ilastik" },
            pattern: "*.{h5}",
            saveAs: { filename -> "${meta.id}_probability_$filename" }
        ]
    }

    withName: "ILASTIK_MULTICUT" {
        ext.when = { params.segmentation_method.split(',').contains('ilastik') }
        publishDir = [
            path: { "${params.outdir}/segmentation/ilastik" },
            pattern: "*.tiff",
            saveAs: { filename -> "${meta.id}_ilastik_$filename" }
        ]
    }

    withName: "CROPHDF5" {
        ext.when = { params.create_training_subset }
        publishDir = [
            path: "${params.outdir}/training_subset/hdf5",
            mode: params.publish_dir_mode,
            pattern: "*{C,c}rop*.{hdf5,h5}"
        ]
        ext.args = [ "",
            "--crop",
            "--nuclei_index 1",
            params.crop_amount                       ? "--crop_amount ${params.crop_amount}"                     : "",
            params.crop_size_x && params.crop_size_y ? "--crop_size ${params.crop_size_x} ${params.crop_size_y}" : "",
            params.crop_nonzero_fraction             ? "--nonzero_fraction ${params.crop_nonzero_fraction}"      : ""
        ].join(" ").trim()
    }

    withName: "CROPTIFF" {
        ext.when = { params.create_training_subset }
        publishDir = [
            path: "${params.outdir}/training_subset/tiff",
            mode: params.publish_dir_mode,
            pattern: "*.{tiff,tif}"
        ]
    }

    withName: "TIFFH5CONVERT" {
        ext.when = { params.segmentation_method.split(',').contains('ilastik') }
        publishDir = [
            path: "${params.outdir}/converted_hdf5",
            pattern: "*.{hdf5,h5}"
        ]
    }

    withName: "CLAHE" {
        ext.prefix = {
            def name = image.name
            def base = name.lastIndexOf('.') != -1 ? name[0..name.lastIndexOf('.') - 1] : name
            return "${meta.id}_${base}_clahe"
        }
        ext.when  = { !params.skip_clahe }
        ext.args  = [ "",
            params.clahe_pyramid_tile ? "--tile-size ${params.clahe_pyramid_tile}" : "",
            params.clahe_cliplimit    ? "--cliplimit ${params.clahe_cliplimit}"    : "",
            params.clahe_nbins        ? "--nbins ${params.clahe_nbins}"            : "",
            params.clahe_pixel_size   ? "--pixel-size ${params.clahe_pixel_size}"  : "",
            params.clahe_kernel       ? "--kernel ${params.clahe_kernel}"          : ""
        ].join(" ").trim()
    }

    withName: "DEEPCELL_MESMER" {
        ext.when  = { params.segmentation_method.split(',').contains('mesmer') }
        ext.args  = [ "",
            params.mesmer_compartment ? "--compartment ${params.mesmer_compartment}" : "",
            params.mesmer_image_mpp   ? "--image-mpp ${params.mesmer_image_mpp}"     : "",
            "--nuclear-channel 0"
        ].join(" ").trim()
        ext.prefix = { "${meta.id}_mesmer_mask" }
        publishDir = [
            path: "${params.outdir}/segmentation/mesmer",
            pattern: "*.tif"
        ]
    }

    withName: "CELLPOSE" {
        singularity.runOptions = "--bind $HOME:$HOME"
        ext.when  = { params.segmentation_method.split(',').contains('cellpose') }
        ext.args = [ "",
            "--channel_axis 0",
            "--no_npy",
            params.cellpose_save_flows       ? "--save_flows"                                           : "",
            params.cellpose_diameter         ? "--diameter ${params.cellpose_diameter}"                 : "",
            params.cellpose_chan             ? "--chan ${params.cellpose_chan}"                         : "",
            params.cellpose_chan2            ? "--chan2 ${params.cellpose_chan2}"                       : "",
            params.cellpose_custom_model     ? ""                                                       : params.cellpose_pretrained_model ? "--pretrained_model ${params.cellpose_pretrained_model}" : "",
            params.cellpose_flow_threshold   ? "--flow_threshold ${params.cellpose_flow_threshold}"     : "",
            params.cellpose_edge_exclude     ? "--exclude_on_edges"                                     : ""
        ].join(" ").trim()
        publishDir = [
            path: "${params.outdir}/segmentation/cellpose",
            pattern: "*_cp_masks.tif",
            saveAs: { filename -> "${meta.id}_cellpose_mask.tif" }
        ]
    }

    withName: "CREATE_ANNDATA" {
        ext.prefix = { "${meta.id}_${meta.segmentation}"}
        publishDir = [
            path: "${params.outdir}/anndata",
            mode: params.publish_dir_mode,
            pattern: "*.{adata}"
        ]
    }
}
