from parallels.core.actions.hosting_settings.transfer_error_documents import TransferErrorDocumentsBase
from parallels.core.utils import plesk_utils
from parallels.plesk.source.plesk.plesk_utils import get_vdirs_list, source_websrvmng_lock
from parallels.plesk.source.plesk.plesk_utils import PathConverter
from parallels.core.utils.error_docs_utils import ErrorDocumentsXMLConverter


class TransferErrorDocuments(TransferErrorDocumentsBase):
	def _get_site_error_documents(self, global_context, subscription, site):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		with source_websrvmng_lock:
			raw_error_documents = plesk_utils.get_error_documents(
				subscription.web_source_server, site.name
			)
		converter = self._create_converter()
		converted_error_documents = converter.convert(subscription, site, raw_error_documents)

		return converted_error_documents

	def _get_site_vdir_error_documents(self, global_context, subscription, site):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		vdirs_list = get_vdirs_list(global_context, subscription, site)
		error_docs = {}
		converter = self._create_converter()
		for vdir in vdirs_list:
			with source_websrvmng_lock:
				raw_error_docs = plesk_utils.get_error_documents(
					subscription.web_source_server, site.name, vdir
				)
			converted_error_docs = converter.convert(subscription, site, raw_error_docs)
			error_docs[vdir] = converted_error_docs

		return error_docs

	@staticmethod
	def _create_converter():
		converter = ErrorDocumentsXMLConverter()
		path_converter = PathConverter()
		converter.set_path_convert_function(path_converter.convert)
		return converter
