import logging

from parallels.common.actions.hosting_settings.transfer_virtual_directories \
	import TransferVirtualDirectoriesBase
from parallels.common.utils.vdir_utils import VirtualDirectoryXMLConverter
from parallels.common.utils.windows_utils import path_join as windows_path_join
from parallels.common.utils.windows_utils import fix_path
from parallels.common.utils.windows_utils import file_exists

logger = logging.getLogger(__name__)


class TransferVirtualDirectories(TransferVirtualDirectoriesBase):
	def _get_site_vdirs_xml(self, global_context, subscription, site):
		"""Get virtual directories XML for specified site

		Returned virtual directories XML should contain all
		paths according to the target server, not source server.
		Returns XML as string.
		"""
		if global_context.helm3_agent.is_fake_domain(site.name):
			return None

		raw_vdir_xml = self.download_vdir_xml(global_context, site, subscription)
		if raw_vdir_xml is None:
			return None

		converter = VirtualDirectoryXMLConverter()
		converter.set_path_convert_function(self._fix_vdir_path)
		converted_vdir_xml = converter.convert(subscription, site, raw_vdir_xml)

		return converted_vdir_xml

	@staticmethod
	def download_vdir_xml(global_context, site, subscription):
		"""Download virtual directories XML from source server

		The XML is pre-created by agent, so the only thing we have
		to do is to take it as is"""

		source_server = global_context.conn.helm3.get_main_source_server()
		with source_server.runner() as runner_source:
			remote_vdir_path = source_server.get_session_file_path(
				"vdir_%s.xml" % site.name
			)
			if not file_exists(runner_source, remote_vdir_path):
				logger.debug(
					"There is no virtual directories XML for site, "
					"virtual directories restoration is skipped for it"
				)
				return None
			vdir_xml = runner_source.get_file_contents(remote_vdir_path)
		return vdir_xml

	@staticmethod
	def _fix_vdir_path(subscription, site, vdir_path):
		"""Convert source virtual directory path to path on target server"""

		new_vhost_path = fix_path(windows_path_join(
			subscription.web_target_server.vhosts_dir,
			subscription.name_idn,
			'httpdocs',
			site.name.encode('idna'),
			vdir_path
		))

		return new_vhost_path
