from parallels.common import messages
import logging

from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.common.utils import plesk_api_utils

logger = logging.getLogger(__name__)


class ChangeSysuserLogin(SubscriptionBackupAction):
	"""Change system user login on source according to target panel"""

	def get_description(self):
		return messages.CHANGE_LOGINS_SYSTEM_USERS_IN_BACKUP

	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.FAILED_CHANGE_LOGIN_SYSTEM_USER_FOR % (subscription.name)

	def get_logging_properties(self):
		return LoggingProperties(info_log=False)

	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 _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		with global_context.safe.try_subscription(subscription.name, messages.FAILED_RESTORE_SUBSCRIPTION_SYSTEM_USERS_LOGIN_1):
			sysuser_name = subscription_backup.phosting_sysuser_name
			if sysuser_name is None:
				return

			ppa_sysuser_name = plesk_api_utils.get_subscription_sysuser_name(
				subscription.panel_target_server.plesk_api(), subscription.name
			)

			if ppa_sysuser_name is None:
				# subscription has no system user on target
				# now we simply ignore that case, but probably it would be
				# better to handle such situation better to avoid issues
				# on the next steps of migration
				return

			if ppa_sysuser_name != sysuser_name:
				subscription_backup.phosting_sysuser_name = ppa_sysuser_name
