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 ChangeSmartermailPassword(SubscriptionBackupAction):
	"""Fix passwords in backup when migrating to SmarterMail mail server"""

	def get_description(self):
		return "Change SmarterMail passwords in backups"

	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 SmarterMail 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
		"""
		if subscription.mail_target_server is None:
			return
		if not subscription.mail_target_server.is_windows():
			return

		for mailuser in subscription_backup.iter_mailboxes():
			if not self._password_is_smartermail_valid(mailuser.password) and mailuser.enabled:
				new_password = global_context.password_holder.get('mailuser', mailuser.full_name)
				mailuser.set_password(new_password)
				global_context.safe.add_issue_subscription(subscription.name, Issue(
					Problem(
						'mailuser_invalid_password_for_windows_mail', Problem.INFO, 
						u"Password of mail user '%s' does not meet Windows mail server requirements." % mailuser.full_name
					),
					u"The mail user '%s' will be transferred with another password: '%s'." % (mailuser.full_name, new_password)
				))


	@staticmethod
	def _password_is_smartermail_valid(password):
		"""Validate password against SmarterMail requirements.
		   Return True if password is valid, False otherwise."""
		return password is not None and len(password) >= 5
