import os

from parallels.core.utils import get_thirdparties_base_path
from parallels.core.utils import windows_utils
from parallels.core.utils import windows_thirdparty


class RemoteNodeSettings(object):
	"""Settings of remote node where paexec will execute commands"""

	def __init__(self, remote_server_ip, username, password):
		self.remote_server_ip = remote_server_ip
		self.username = username
		self.password = password


class PAExecCommand(object):
	"""Wrapper around paexec command

	For more information on paexec, visit http://www.poweradmin.com/paexec/
	"""
	def __init__(self, migrator_server, remote_node_settings):
		self._migrator_server = migrator_server
		self._remote_node_settings = remote_node_settings

	def run(self, executable, arguments=None, copy_program=False, do_not_wait=False, is_unchecked=False):
		passwords_file = os.path.abspath(
			self._migrator_server.get_session_file_path(
				'node-password-%s' % self._remote_node_settings.remote_server_ip
			)
		)

		command_parts = [
			'cd "%s" &&"%s"' % (
				get_thirdparties_base_path(),
				windows_thirdparty.get_paexec_bin(),
			),
			r'\\%s' % (self._remote_node_settings.remote_server_ip,),
			'-u %s' % (self._remote_node_settings.username,),
			'-p@ "%s"' % (passwords_file,),
			"-p@d"  # delete passwords file after usage
		]
		if do_not_wait:
			command_parts.append("-d")

		if copy_program:
			command_parts.append("-c")
			# by default - overwrite if file already exists
			command_parts.append("-f")

		command_parts.append(executable)

		if arguments is not None:
			command_parts.append(arguments)

		with self._migrator_server.runner() as runner:
			runner.upload_file_content(
				passwords_file,
				self._remote_node_settings.password
			)

		command = windows_utils.cmd_command(" ".join(command_parts))
		with self._migrator_server.runner() as runner:
			if is_unchecked:
				runner.sh_unchecked(command)
			else:
				runner.sh(command)