import logging

from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.utils import subscription_filter
from parallels.utils import ilen

logger = logging.getLogger(__name__)


class ResetPermissions(SubscriptionAction):
	"""Reset file permissions on Windows like Plesk restore does"""
	
	def get_description(self):
		return "Fix file permissions for Windows"

	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 file permissions for 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 filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return subscription_filter.windows_with_virtual_hosting(
			subscription
		)

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

		sysuser_name = subscription.converted_backup.get_phosting_sysuser_name()
		if sysuser_name is not None:
			if ilen(subscription.raw_backup.iter_sites()) > 1:
				# there are subdomains or/and addon domains
				logger.debug(u"Update webspace subdomains security for the '%s' subscription",  subscription.name_idn)
				global_context.import_api.update_webspace_subdomains_security_metadata_location(subscription.name_idn)

		logger.debug(u"Repair permissions for the '%s' subscription", subscription.name_idn)
		global_context.import_api.repair_webspace_security(subscription)
