from parallels.hosting_check.utils.text_utils import format_string

class Powershell(object):
	def __init__(self, runner, input_format_none=False):
		"""
		Arguments:
		- runner - runner instance to Windows node where you are going
			to execute Powershell scripts. Instance of 
			hosting_check.ServerRunnerBase or other compatible class. 
		- input_format_none, boolean. If True, "-InputFormat none" will be specified 
			to Powershell interpreter, which is required 
			in certain conditions for powershell not to hang
			See http://stackoverflow.com/questions/4238192/running-powershell-from-msdeploy-runcommand-does-not-exit/ 
			for more details
		"""
		self.runner = runner
		self.input_format_none = input_format_none

	def execute_script_unchecked(self, script_path, args):
		"""Execute script with Powershell
		Arguments:
		- script_path - path to the script on the remote server
		- args - dictionary of arguments to pass to the script
		for example, if you pass {'param1': 'value1', 'param2': 'value2'}, you can obtain the values in the powershell script by the following code:
		param(
			[string]$param1,
			[string]$param2
		)
		"""

		cmd = self.get_command_string(script_path, args)
		return self.runner.sh_unchecked(cmd)

	def get_command_string(self, script_path, args):
		"""Execute script with Powershell
		Arguments:
		- script_path - path to the script on the remote server
		- args - dictionary of arguments to pass to the script
		for example, if you pass {'param1': 'value1', 'param2': 'value2'}, you can obtain the values in the powershell script by the following code:
		param(
			[string]$param1,
			[string]$param2
		)
		"""
		args_list = args.items()
		args_keys = [arg[0] for arg in args_list]
		args_values = [arg[1] for arg in args_list]

		if self.input_format_none:
			input_format_arg = ['-InputFormat none']  
		else: 
			input_format_arg = []

		cmd = u" ".join(
			[u"powershell -ExecutionPolicy Unrestricted"] + \
			input_format_arg + \
			['-File {script_path}'] + \
			[
				u"-%s {arg%s}" % (name, i) 
				for i, name in enumerate(args_keys)
			]
		)
		cmd_args = dict(script_path=script_path)
		for i, value in enumerate(args_values):
			cmd_args[u"arg%s" % (i,)] = value

		return _format_command(cmd, cmd_args)

def _format_command(template, cmd_args):
	qkw = dict((k, _quote_arg(unicode(v))) for k, v in cmd_args.iteritems())
	return format_string(unicode(template), qkw)

def _quote_arg(arg):
	return '"%s"' % arg.replace('"', '""')
