#!/usr/bin/env python
#main
import sys
import argparse
import textwrap
import signal
import time
import traceback
import os
import shutil
import tempfile

def keyboard_handler(sig, frame):#Catch keyboard interupt and end processors
	sys.stdout.write("\r[ERROR] parabam interrupted by user")
	sys.exit(0)

def get_unique_tempdir():
	return tempfile.mkdtemp(prefix="parabam-tmp-",dir=".")

def die_gracefully(temp_dir):
	if not temp_dir == "." or not temp_dir == "" or not temp_dir == "./": 
		shutil.rmtree(temp_dir)

if __name__ == "__main__":

	signal.signal(signal.SIGINT, keyboard_handler) #Handle KeyboardInterrupt gracefully

	argument_len = len(sys.argv) >= 2

	progs = {"stat":"command.stat",
			"subset":"command.subset"}

	printInfo = False

	if argument_len:

		file_path = sys.argv[0]
		command = sys.argv[1]

		temp_dir = get_unique_tempdir()

		if command in progs:
			#Load the command using the command line
			module = __import__("parabam.%s" % (progs[command],), fromlist=[''])
			sys.argv = sys.argv[1:] #Remove command from arguments.
			try:
				interface = module.Interface(temp_dir)
				interface.run_cmd(interface.get_parser())
			except SystemExit:
				print " "
				print "[Status] parabam is quitting gracefully\n"
			except BaseException as exception:
				print " "
				print "[Error] parabam stopped unexpecedtly, sorry!"
				traceback.print_exception(*sys.exc_info())
				die_gracefully(temp_dir)
				raise
		else:
			print "\nCommand not recognised. Refer to manual below:\n"
			printInfo = True
		die_gracefully(temp_dir)
	else:
		printInfo = True
	
	if printInfo:
		print textwrap.dedent('''\
		
		parabam
		----------------------------------------------------------------

		About: 
			Parabam - analyse bam file in parallel

		Usage:
			parabam <command> [options] instruction:{Python} input:{BAM} output:{BAM/CSV}

		Command:
			stat\t Genereate stats regarding the BAM file
			subset\t Create a subsetted BAM file

    	'''.expandtabs())
