#!/usr/local/bin/python2.7

import locale
import sys
import traceback

from optparse import OptionParser

from bugz import cli, __version__
from bugz.cli import BugzError, PrettyBugz

def main():
	if len(sys.argv) < 2:
		PrettyBugz.help()
		sys.exit(-1)

	cmd = sys.argv[1]

	parser = OptionParser(version = '%%prog %s' % __version__)

	global_opts = PrettyBugz.options
	for x in global_opts.values():
		parser.add_option(x)

	if cmd == '--help' or cmd == '-h' or cmd == 'help':
		PrettyBugz.help()
		sys.exit(0)
	elif cmd == '--version' :
		parser.print_version()
		sys.exit(0)

	cmd_func = getattr(PrettyBugz, cmd, None)
	if cmd_func is None:
		print '!! Error: Unable to recognise command: %s' % cmd
		print
		PrettyBugz.help()
		sys.exit(-1)

	cmd_options = getattr(cmd_func, "options", {})
	cmd_args = getattr(cmd_func, "args", "[options]")
	parser.set_description(cmd_func.__doc__)
	parser.set_usage('%%prog %s %s' % (cmd, cmd_args))

	for x in cmd_options.values():
		parser.add_option(x)

	# parse options
	opts, args = parser.parse_args(sys.argv[2:])

	# separate bugz options and cmd options
	bugz_kwds = {}
	for name, opt in global_opts.items():
		try:
			bugz_kwds[name] = getattr(opts, name)
		except AttributeError:
			pass

	cmd_kwds = {}
	for name, opt in cmd_options.items():
		try:
			cmd_kwds[name] = getattr(opts, name)
		except AttributeError:
			pass

	try:
		bugz = PrettyBugz(**bugz_kwds)
		getattr(bugz, cmd)(*args, **cmd_kwds)

	except BugzError, e:
		print ' ! Error: %s' % e
		print
		parser.print_help()
		sys.exit(-1)

	except TypeError, e:
		print ' ! Error: Incorrect number of arguments supplied'
		print
		traceback.print_exc()
		parser.print_help()
		sys.exit(-1)

	except RuntimeError, e:
		print ' ! Error: %s' % e
		sys.exit(-1)

	except KeyboardInterrupt:
		print
		print 'Stopped.'
		sys.exit(-1)

	except:
		raise

if __name__ == "__main__":
	main()
