from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.plesk_api import operator as plesk_ops


class ResetHostingForSubscriptionWithoutHosting(SubscriptionAction):
	"""When subscription is provisioned by POA, it always has physical hosting turned on. We disable it here.

	If domains has another type of hosting (not physical) it will be switched during
	restoration from backup. However, if domains has no hosting then Plesk leaves physical
	hosting after restoration from backup.
	Thus it is needed to manually switch off hosting for such subscriptions.
	"""
	def get_description(self):
		return "Reset hosting for subscriptions without hosting"

	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 filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return subscription.converted_backup.hosting_type == 'none'

	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 reset hosting for subscriptions without hosting '%s'" % subscription.name

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		results = subscription.panel_target_server.plesk_api().send(plesk_ops.SubscriptionOperator.Set(
			filter=plesk_ops.SubscriptionOperator.FilterByName([subscription.name]),
			hosting=plesk_ops.SubscriptionHostingNone(),
			limits=None,
		), plesk_disable_provisioning='true')
		for result in results:
			result.check()