include { BOWTIE2_ALIGNMENT } from '../../modules/local/hicstuff/align_bowtie2'
include { FRAGMENT_ENZYME } from '../../modules/local/hicstuff/fragment_enzyme'
include { BAM2PAIRS } from '../../modules/local/hicstuff/bam2pairs'
include { BUILD_MATRIX } from '../../modules/local/hicstuff/build_matrix'

// Paired-end to Single-end
def pairToSingle(row, mates) {
    def meta = row[0].clone()
    meta.single_end = true
    meta.mates = mates
    if (mates == "R1") {
        return [meta, [ row[1][0]] ]
    }else if (mates == "R2"){
        return [meta, [ row[1][1]] ]
    }
}

// Single-end to Paired-end
def singleToPair(row){
    def meta = row[0].clone()
    meta.remove('mates')
    meta.single_end = false
    return [ meta, row[1] ]
}

workflow HICSTUFF_SUB {

    take:
    reads
    index
    ligation_site
    digestion
    fasta

    main:

    // Align each mates separetly and add mates information in [meta]
    ch_reads_r1 = reads.map{ it -> pairToSingle(it,"R1") }
    ch_reads_r2 = reads.map{ it -> pairToSingle(it,"R2") }
    ch_reads = ch_reads_r1.concat(ch_reads_r2)

    BOWTIE2_ALIGNMENT(
        ch_reads,
        index.collect()
    )

    FRAGMENT_ENZYME(
        digestion,
        fasta
    )

    BAM2PAIRS(
        BOWTIE2_ALIGNMENT.out.bam.combine(BOWTIE2_ALIGNMENT.out.bam)
            .map {
                meta1, bam1, meta2, bam2 ->
                    meta1.id == meta2.id && meta1.mates == "R1" && meta2.mates == "R2" ? [ meta1,  bam1,  meta2, bam2 ] : null
        },
        FRAGMENT_ENZYME.out.info_contigs.collect(),
        digestion,
        fasta.collect()
    )

    BUILD_MATRIX(
        BAM2PAIRS.out.idx_pairs,
        FRAGMENT_ENZYME.out.fragments_list
    )
}