#!/usr/bin/env python
# -*- coding: utf-8

import os
import sys
import pysam

import anvio
import anvio.terminal as terminal

from anvio.errors import ConfigError


__author__ = "A. Murat Eren"
__copyright__ = "Copyright 2015, The anvio Project"
__credits__ = []
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "A. Murat Eren"
__email__ = "a.murat.eren@gmail.com"
__status__ = "Development"


pp = terminal.pretty_print 


def init_bam_file(input_file_path, output_file_path = None, already_sorted = False):
        progress = terminal.Progress()
        run = terminal.Run()

        input_file_path = os.path.abspath(input_file_path)
        if output_file_path:
            output_file_path = os.path.abspath(output_file_path)
        else:
            output_file_path = input_file_path + '-sorted'

        output_directory = os.path.dirname(output_file_path)

        if not os.access(output_directory, os.W_OK):
            raise ConfigError, "You do not have write permission for the output directory: '%s'" % output_directory

        if not already_sorted:
            progress.new('SORT')
            progress.update('Sorting BAM File... May take a while depending on the size.')
            pysam.sort(input_file_path, output_file_path)
            progress.end()
            run.info('Sorted BAM File', output_file_path)
            sorted_file_path = output_file_path + '.bam'
            if not os.path.exists(sorted_file_path):
                raise ConfigError, "Sorry. Something went wrong. Samtools thinks it generated the sorted output, yet it is not there :("
        else:
            sorted_file_path = input_file_path


        progress.new('INDEX')
        progress.update('Indexing BAM File...')
        pysam.index(sorted_file_path)
        progress.end()
        run.info('Indexed BAM File', sorted_file_path, mc='green')


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Sort/Index BAM files')
    parser.add_argument('input_file', metavar = 'BAM_FILE',
                        help = 'BAM file to analyze')
    parser.add_argument('--sorted', action = 'store_true', default = False,
                        help = 'Flag to define whether BAM file is already sorted')
    parser.add_argument('-o', '--output-file', default = None,
                        help = 'Output file path for sorted/indexed BAM file')
    #parser.add_argument('--overwrite', action = 'store_true', default = False,
    #                    help = 'When used, the sorted BAM file overwrites the original\
    #                    file. Do not use if you are not sure')

    args = parser.parse_args()

    try:
        sys.exit(init_bam_file(input_file_path = args.input_file,
                               output_file_path = args.output_file,
                               already_sorted = args.sorted))
    except ConfigError, e:
        print e
        sys.exit(-1)
