from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.common.checking import Issue
from parallels.common.checking import Problem


class ChangeSysuserPassword(SubscriptionBackupAction):
	"""Sysusers may have passwords not valid for current Plesk.
	   In this case, change password and inform provider in the end of migration.
	"""

	def get_description(self):
		return "Change non-valid system user password"

	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 change non-valid system user passwords 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 get_logging_properties(self):
		return LoggingProperties(info_log=False)

	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
		"""
		for sysuser in subscription_backup.iter_system_users():
			if not self._password_is_valid(sysuser.password):
				new_password = global_context.password_holder.get('system_user', sysuser.name)
				if sysuser.password is not None:
					global_context.safe.add_issue_subscription(subscription.name, Issue(
						Problem('invalid_system_password', Problem.WARNING, u"Password of system user '%s' does not meet PPA requirements." % sysuser.name),
						u"The system user '%s' will be transferred with another password: '%s'. You can change the password for the corresponding system/FTP/web user in PPA once the content transfer is finished." % (sysuser.name, new_password)
					))
				sysuser.set_password(new_password, 'plain')

	@staticmethod
	def _password_is_valid(password):
		"""Validate password agains Plesk requirements
		Return True if password is valid, False otherwise.
		"""
		if password is None:
			return False
		if password.type == 'plain':
			for c in password.text:
				if any([ord(c) >= 128, c == "'", c == " "]):
					return False
		return True
