import argparse

from parallels.common.cli.migrator_cli import Command, CommandTypes, \
		MigratorHelpCommand, MigratorShellCommand, MigratorScriptCommand, \
		create_arguments_parser, run as run_migrator
from parallels.common.cli.import_cli import _get_list_options
from .migrator import Migrator

def run(script_dir, args):
	run_migrator(
		args_parser=_create_migrator_arguments_parser(script_dir),
		create_migrator_func=Migrator,
		args=args,
	)

def _create_migrator_arguments_parser(script_dir):
	indent = ' ' * 4

	migration_list_file_opt = argparse.ArgumentParser(add_help=False)
	migration_list_file_opt.add_argument(
		'--move-list-file', 
		help=u"Move list filename, default value is $session_dir/move-list"
	)

	commands= []

	# standard commands - help, shell, script
	commands.extend([
		MigratorHelpCommand(_get_migrator_command_name(), commands, indent),
		MigratorShellCommand(),
		MigratorScriptCommand(),
	])

	# migrator-specific commands
	for command in Migrator.flat_iter_commands_tree(Migrator.get_commands_tree()):
		commands.append(Command(
			command.name, command.command_type,
			command.brief_description,
			lambda m, o, command_name=command.name: m.execute_command(command_name, o),
			[migration_list_file_opt]
		)
	)
	# Used by bash completion
	get_options_opts = argparse.ArgumentParser(add_help=False)
	get_options_opts.add_argument('--command')
	commands.append(
		Command(
			'list-options', CommandTypes.MICRO,
			u"Return list of available options",
			lambda o: _get_list_options(commands, o),
			[get_options_opts],
			migrator_required=False
			),
	)
	
	return create_arguments_parser(
		migrator_command_name=_get_migrator_command_name(),
		description=u"Move subscriptions between PPA Apache nodes",
		commands=commands,
		script_dir=script_dir,
		indent=indent
	)

def _get_migrator_command_name():
	return 'ppa-move-subscriptions'
