#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 19 March  2012
@author: tcezard
'''
import sys
import os
import logging
from optparse import OptionParser
from glob import glob

from utils import utils_logging
import command_runner
from RAD_merge_bam_files import merge_bam_files



#get the path to the current script to infer the path to RAD_set_read1_consensus_to_read2.py
RADmapper_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
path_to_picard = os.path.join(RADmapper_dir,"picard")
mergeSamFilesWithCat_jar=os.path.join(path_to_picard,'MergeSamFilesWithCat.jar')

##### Generic merging functions
def merge_bam_files_with_picard(list_of_file, output_file=None, **kwargs):
    """This is a generic merging function for bam files.
    It assumes that all the bam file comes from mapping to independent contigs"""

    if not output_file:
        #Create a generic name and put it in the current working directory
        working_directory=os.getcwd()
        i=1
        output_file_template=os.path.join(working_directory,'tmp_merge_bam_%s.bam')
        output_file=output_file_template%i
        while os.path.exists(output_file):
            i+=1
            output_file=output_file_template%i
    command = 'java -jar -Xmx2G %s VALIDATION_STRINGENCY=SILENT CAT_SEQUENCE_DICTIONARIES=True USE_THREADING=True O=%s '%(mergeSamFilesWithCat_jar,output_file)
    inputs=['I=%s'%file for file in list_of_file]
    command += ' '.join(inputs)
    return_code=command_runner.run_command(command)
    if return_code==0:
        return output_file
    else:
        return None


def concatenate_file(list_of_file,output_file=None, **kwargs):
    """This is a generic merging function for concatenating text files.
    It can take a filter keyword argument to grep out using the provided value"""
    if not output_file:
        #Create a generic name and put it in the current working directory
        if kwargs.has_key('output_dir'):
            working_directory = kwargs.get('output_dir')
        else:
            working_directory = os.getcwd()
        i=1