from parallels.plesks_migrator import messages
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 messages.ACTION_RESET_PERMISSIONS_DESCRIPTION

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return messages.ACTION_RESET_PERMISSIONS_FAILURE % 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(messages.UPDATE_WEBSPACE_SUBDOMAINS_SECURITY,  subscription.name_idn)
				global_context.import_api.update_webspace_subdomains_security_metadata_location(subscription)

		logger.debug(messages.REPAIR_PERMISSIONS_FOR_SUBSCRIPTION, subscription.name_idn)
		global_context.import_api.repair_webspace_security(subscription)
