from parallels.core.utils.vdir_utils import VirtualDirectoryXMLConverter
from parallels.core.actions.hosting_settings.transfer_virtual_directories import TransferVirtualDirectoriesBase
from parallels.source.plesk.plesk_utils import PathConverter, source_websrvmng_lock
from parallels.core.utils.plesk_utils import get_vdir_info


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

		Returned virtual directories XML contains all
		paths according to the target server, not source server.
		Returns XML as string.

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		with source_websrvmng_lock:
			raw_vdir_info = get_vdir_info(subscription.web_source_server, site.name).encode('utf-8')
		self._save_raw_vdir_xml(global_context, site, raw_vdir_info)

		converter = VirtualDirectoryXMLConverter()
		converter.set_reserved_vdirs(self._get_reserved_vdirs())
		path_converter = PathConverter()
		converter.set_path_convert_function(path_converter.convert)
		converted_vdir_info = converter.convert(subscription, site, raw_vdir_info)
		self._save_converted_vdir_xml(global_context, site, converted_vdir_info)

		return converted_vdir_info

	@staticmethod
	def _save_converted_vdir_xml(global_context, site, vdir_info_xml):
		filename = global_context.session_files.get_converted_vdir_xml(
			site.name
		)
		with open(filename, 'wb') as f:
			f.write(vdir_info_xml)

	@staticmethod
	def _save_raw_vdir_xml(global_context, site, vdir_info_xml):
		filename = global_context.session_files.get_raw_vdir_xml(
			site.name
		)
		with open(filename, 'wb') as f:
			f.write(vdir_info_xml)

	@staticmethod
	def _get_reserved_vdirs():
		"""Get list of directories to remove from vdirs XML
		The list is taken from Plesk's
		RestoreVirtualDirectories function at
		windows/binary/plesk-utils/PMM/psadumpagent/RestoreEnv.cs
		"""
		return (
			'_vti_bin',
			'jakarta',
			'JRunScripts',
			'CFIDE',
			'cfdocs',
			'cgi-bin',
			'plesk-stat',
			'sitepreview'
		)
