#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import pipes
import click

from . import _fileio, _pairsam_format, cli, _headerops

UTIL_NAME = 'pairsam_markasdup'

@cli.command()
@click.argument(
    'pairsam_path', 
    type=str,
    required=False)
@click.option(
    "-o", "--output", 
    type=str, 
    default="", 
    help='output .pairsam file.'
        ' If the path ends with .gz, the output is bgzip-compressed.'
        ' By default, the output is printed into stdout.')

def markasdup(pairsam_path, output):
    '''tag all pairsam entries with a duplicate tag.

    PAIRSAM_PATH : input .pairsam file. If the path ends with .gz, the input is
    gzip-decompressed. By default, the input is read from stdin.
    '''
    markasdup_py(pairsam_path, output)

def markasdup_py(pairsam_path, output):
    instream = (_fileio.auto_open(pairsam_path, mode='r') 
                if pairsam_path else sys.stdin)
    outstream = (_fileio.auto_open(output, mode='w') 
                 if output else sys.stdout)
 

    header, body_stream = _headerops.get_header(instream)
    header = _headerops.append_new_pg(header, ID=UTIL_NAME, PN=UTIL_NAME)
    outstream.writelines((l+'\n' for l in header))


    for line in body_stream:
        cols = line[:-1].split(_pairsam_format.PAIRSAM_SEP)
        cols[_pairsam_format.COL_PTYPE] = 'DD'
        
        if (len(cols) > _pairsam_format.COL_SAM1) and (len(cols) > _pairsam_format.COL_SAM2):
            for i in (_pairsam_format.COL_SAM1,
                      _pairsam_format.COL_SAM2):
                    
                # split each sam column into sam entries, tag and assemble back
                cols[i] = _pairsam_format.INTER_SAM_SEP.join(
                    [mark_sam_as_dup(sam) 
                     for sam in cols[i].split(_pairsam_format.INTER_SAM_SEP)
                    ])

        outstream.write(_pairsam_format.PAIRSAM_SEP.join(cols))
        outstream.write('\n')

    if instream != sys.stdin:
        instream.close()
    if outstream != sys.stdout:
        outstream.close()

def mark_sam_as_dup(sam):
    '''Tag the binary flag and the optional pair type field of a sam entry
    as a PCR duplicate.'''
    samcols = sam.split(_pairsam_format.SAM_SEP)

    if len(samcols) == 1:
        return sam

    samcols[1] = str(int(samcols[1]) | 1024)

    for j in range(11, len(samcols)):
        if samcols[j].startswith('Yt:Z:'):
            samcols[j] = 'Yt:Z:DD'
    return _pairsam_format.SAM_SEP.join(samcols)


if __name__ == '__main__':
    markasdup()

@@ -132,16 +132,35 @@
 eaderops
+, common_io_options
 %0A%0AUTIL_N
@@ -407,24 +407,32 @@
 nds with .gz
+ or .lz4
 , the output
@@ -439,14 +439,21 @@
  is 
+p
 bgzip-
+/lz4c-
 comp
@@ -521,16 +521,36 @@
 out.')%0A%0A
+@common_io_options%0A%0A
 def mark
@@ -571,24 +571,34 @@
 path, output
+, **kwargs
 ):%0A    '''ta
@@ -832,16 +832,26 @@
 , output
+, **kwargs
 )%0A%0Adef m
@@ -882,16 +882,26 @@
 , output
+, **kwargs
 ):%0A    i
@@ -955,110 +955,384 @@
 ='r'
-) %0A                if pairsam_path else sys.stdin)%0A    outstream = (_fileio.auto_open(output, mode='w'
+, %0A                                  nproc=kwargs.get('nproc_in'),%0A                                  command=kwargs.get('cmd_in', None)) %0A                if pairsam_path else sys.stdin)%0A    outstream = (_fileio.auto_open(output, mode='w', %0A                                   nproc=kwargs.get('nproc_out'),%0A                                   command=kwargs.get('cmd_out', None)
 ) %0A 
@@ -1373,18 +1373,16 @@
 .stdout)
-%0A 
 %0A%0A    he
@@ -1559,17 +1559,16 @@
 ader))%0A%0A
-%0A
     for 
@@ -1611,13 +1611,17 @@
 line
-%5B:-1%5D
+.rstrip()
 .spl

add lz4 and custom compression