import logging

from contextlib import contextmanager

from parallels.core import version_tuple
from parallels.ppa.utils import poa_utils
from parallels.plesk.source.plesk.server import PleskSourceServer
from parallels.core.utils.common import cached

from parallels.shcm_web_sn.source.shcm_web_sn import messages

logger = logging.getLogger(__name__)


class SHCMMoveWebspacesSourceServer(PleskSourceServer):
	def __init__(self, node_id, node_settings, migrator_server, plesk_version, mn_server, vhosts_dir=None):
		"""
		Plesk source server with possibility to specify custom vhosts dir.

		In SHM/SHCM there is possibility to group webspaces into partitions. Different partitions or groups of
		partitions can be available on different apache SNs.

		Typical custom vhosts dir is /var/www/vhosts/<partition_name>

		:param node_id: source node id
		:param node_settings: node settings from config
		:param migrator_server: server where migrator is run
		:param plesk_version: Plesk version on source (xx.xx.xx)
		:param mn_server: PPA management node
		:param vhosts_dir: Custom vhosts dir path
		"""
		super(SHCMMoveWebspacesSourceServer, self).__init__(
				node_id, node_settings, migrator_server
		)
		self._vhosts_dir = vhosts_dir
		self.plesk_version_string = plesk_version
		self.mn_server = mn_server
		self.ppa_host_id = poa_utils.get_host_id_by_ip(self.mn_server.poa_api(), self.ip())
		logger.debug(messages.PPA_HOST_ID_OF_WEB_SERVICE.format(host_id=self.ppa_host_id))

	@property
	@cached
	def plesk_version(self):
		return version_tuple(self.plesk_version_string)

	@contextmanager
	def runner(self):
		"""Get runner object to execute commands on the source server"""
		if self.is_windows():
			with self.mn_server.ppa_windows_node_runner(self.ppa_host_id) as runner:
				yield runner
		else:
			with self.mn_server.ppa_unix_node_runner(self.ppa_host_id) as runner:
				yield runner

	@property
	@cached
	def vhosts_dir(self):
		return self._vhosts_dir if self._vhosts_dir else super(SHCMMoveWebspacesSourceServer, self).vhosts_dir()
