from contextlib import contextmanager

from parallels.core.run_command import LocalUnixRunner
from parallels.ppa.utils import poa_utils
from parallels.core.utils.session_dir import UnixSessionDir, WindowsSessionDir
from parallels.ppa.connections.target_connections import PPATargetConnections
import parallels.plesk.config as connections_config
from parallels.ppa.run_command.unix_hcl_runner import UnixHclRunner
from parallels.ppa.run_command.windows_hcl_runner import WindowsHclRunner
from parallels.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 WindowsHclRunner(
				LocalUnixRunner(), self._destination_node_id,
				self.get_ppa_node_description(self._destination_node_id)
			)
		else:
			yield UnixHclRunner(
				LocalUnixRunner(), self._destination_node_id,
				self.get_ppa_node_description(self._destination_node_id)
			)
