import itertools

from parallels.common.actions.base.subscription_backup_action \
	import SubscriptionBackupAction
from parallels.common.target_panels import TargetPanels


class FTPUserLogin(SubscriptionBackupAction):
	"""Replace '.' and '-' symbols in FTP user login names with '_'

	That is necessary to conform to PPA system user naming rules.
	"""
	def filter_subscription(self, global_context, subscription):
		# necessary on PPA only, no need to change logins when
		# migrating to Plesk
		return global_context.target_panel == TargetPanels.PPA

	def get_description(self):
		return "Change FTP user logins so they conform to PPA rules"

	def get_failure_message(self, global_context, subscription):
		return (
			"Failed to change FTP user logins so they conform to PPA rules. "
			"FTP users may be restored incorrectly"
		)

	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_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		for user in itertools.chain(
			subscription_backup.iter_ftp_users(),
			subscription_backup.iter_additional_system_users()
		):
			user.name = (
				user.name
					.replace('.', '_')
			)
