rule clean_ngs:
    """Clean_ngs (adapter removal)

    Required input:
        - __clean_ngs__input

    Required output:
        - __clean_ngs__output,
        - __clean_ngs__rej_files

    Other requirements:
        -  __clean_ngs__logs

    Required configuration:
        .. code-block:: yaml

            cutadapt:
                do: yes
                tool_choice: clean_ngs
                design: "%(adapter_design)s"
                adapter_choice: "%(adapter_type)s"
                fwd: "%(adapter_fwd)s"
                rev: "%(adapter_rev)s"
                m: 20   # cutoff
                mode: "g"   # g for 5' adapter, a for 3' and b for both 5'/3'
                quality: "30"
                options: "-O 6 --trim-n"

    References:
        https://github.com/PF2-pasteur-fr/clean_ngs
    """


    input:
        __clean_ngs__input
    log:
        __clean_ngs__logs
    output:
        fastq = __clean_ngs__output,
        rej_files = __clean_ngs__rej_files
    params:
        adapters = config['adapter_removal']['fwd'],
        min_len = config['adapter_removal']['m'],
        quality = config['adapter_removal']['quality']
        options =  config['adapter_removal']['options']
    run:

        unzip_file = [filename[:-3] for filename in input.fastq]
        cmd = "clean_ngs -adf {params.adapters} -l {params.min_len} -q5 {params.quality} {params.options}"
        # paired end or single end unzip
        #input
        if len(input.fastq) == 2:
            fastq_input = "-if1 " + unzip_file[0] + " -if2 " + unzip_file[1]
        else:
            fastq_input = "-if1 " + unzip_file[0]
        cmd = cmd + " " + fastq_input
        #output
        if len(input.fastq) == 2:
            fastq_output = "-of1 " + output.fastq[0] + " -of2 " + output.fastq[1]
        else:
            fastq_output = "-of1 " + output.fastq[0]
        cmd = cmd + " " + fastq_output
        #rejected files
        if len(input.fastq) == 2:
            fastq_rejected = "-rf1 " + output.rej_files[0] + " -rf2 " + output.rej_files[1]
        else:
            fastq_rejected = "-rf1 " + output.rej_files[0]
        cmd = cmd + " " + fastq_rejected


        shell("unpigz -fk {input.fastq} -p {threads} && " + cmd )

