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

import os
import sys
import pysam

import anvio
import anvio.terminal as terminal
import anvio.filesnpaths as filesnpaths

from anvio.errors import ConfigError
from anvio.errors import FilesNPathsError


__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"


progress = terminal.Progress()
run = terminal.Run()
pp = terminal.pretty_print 


def init_bam_file(input_file_path, output_file_path = None):
    """sort and index a BAM file"""

    input_file_path = os.path.abspath(input_file_path)

    if output_file_path:
        output_file_path = os.path.abspath(output_file_path)
        if not output_file_path.endswith('.bam'):
            raise ConfigError("The output file should end with extension '.bam'.")
    else:
        output_file_path = input_file_path + '-sorted.bam'

    filesnpaths.is_file_exists(input_file_path)
    filesnpaths.is_output_file_writable(output_file_path)

    progress.new('SORT')
    progress.update('Sorting BAM File... May take a while depending on the size.')

    pysam.sort("-o", output_file_path, input_file_path)
    progress.end()

    run.info('Sorted BAM File', output_file_path)
    if not os.path.exists(output_file_path):
        raise ConfigError("Sorry. Something went wrong. Samtools thinks it generated the sorted output, yet it is not there :(")

    progress.new('INDEX')
    progress.update('Indexing BAM File...')
    pysam.index(output_file_path)
    progress.end()
    run.info('BAM File Index', output_file_path + '.bai', 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(*anvio.A('output-file'), **anvio.K('output-file'))

    args = parser.parse_args()

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