from contextlib import contextmanager
from parallels.core import run_command
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.shcm_web_sn.connections.target_server import SHCMMoveWebspacesTargetServer
from parallels.core.utils.common import cached


class SHCMWebSNTargetConnections(PPATargetConnections):
	def __init__(self, config):
		super(SHCMWebSNTargetConnections, 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 SHCMMoveWebspacesTargetServer(self, self._destination_node_id, self._destination_settings.ip)

	@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):
		yield run_command.LocalUnixRunner()
