from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.actions.hosting_settings.import_backups import ImportedBackups
from parallels.common.utils.restore_hosting_utils import get_restore_hosting_utils


class RestoreSubscriptionHostingSettings(SubscriptionAction):
	def get_description(self):
		return "Restore hosting settings of subscription"

	def filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return True

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return "Failed to restore hosting settings of subscription '%s'" % subscription.name

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed for a subscription, migration tool
		won't run the next operations for the subscription.

		:rtype: bool
		"""
		return False

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		imported_backup = ImportedBackups.get_instance().get_by_backup(subscription.full_converted_backup)
		subscription_backup_xml = imported_backup.get_domain_xml_path(subscription.name_idn)

		restore_hosting_utils = get_restore_hosting_utils(subscription.panel_target_server)
		restore_hosting_utils.restore_hosting_settings(
			subscription.name, subscription_backup_xml, global_context.safe,
			settings_description=u"hosting settings",
			disable_apsmail_provisioning=subscription.is_mail_assimilate
		)