from contextlib import contextmanager
from parallels.core import run_command
from parallels.core.utils import poa_utils
from parallels.core.utils.session_dir import UnixSessionDir, WindowsSessionDir
from parallels.target.ppa.connections.target_connections import PPATargetConnections
import parallels.core.migrator_config as connections_config
from parallels.target.shm_web_sn.connections.target_server import PPAMoveWebspacesTargetServer
from parallels.core.utils.common import cached


class PPAWebSNTargetConnections(PPATargetConnections):
	def __init__(self, config):
		super(PPAWebSNTargetConnections, self).__init__(config)

		self._destination_settings = connections_config.read_target_plesk_settings(config, 'Destination')
		self._destination_node_id = poa_utils.get_host_id_by_ip(self.poa_api(), self._destination_settings.ip)

		if self.is_windows:
			self._session_dir = WindowsSessionDir(self.main_node_runner, self._ppa_settings.windows_session_dir)
		else:
			self._session_dir = UnixSessionDir(self.main_node_runner, self._ppa_settings.unix_session_dir)

	@property
	@cached
	def plesk_server(self):
		return PPAMoveWebspacesTargetServer(self)
	
	@property
	def is_windows(self):
		return self._destination_settings.is_windows

	@property
	def is_local(self):
		return self._destination_settings.is_local

	@contextmanager
	def main_node_runner(self):
		if self.is_windows:
			yield run_command.WindowsHclRunner(run_command.LocalUnixRunner(), self._destination_node_id,
				self.get_ppa_node_description(self._destination_node_id))
		else:
			yield run_command.UnixHclRunner(run_command.LocalUnixRunner(), self._destination_node_id,
				self.get_ppa_node_description(self._destination_node_id))
