import itertools
import logging
from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties import LoggingProperties

logger = logging.getLogger(__name__)


class ChangeSubscriptionMailIPs(SubscriptionBackupAction):
	"""Change mail IPs according to subscription's hosting addresses"""

	def get_description(self):
		return messages.CHANGE_MAIL_IPS_IN_BACKUP

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.FAILED_TO_CHANGE_MAIL_IPS_IN_BACKUP

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

	def _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		all_target_ips = subscription.panel_target_server.get_all_ips(global_context)
		ip_address_to_type = {ip.ip_address: ip.ip_type for ip in all_target_ips}

		for domain in itertools.chain(
			[subscription_backup],
			subscription_backup.iter_addon_domains()
		):
			for mail_object in [domain.mailsystem, domain.maillists]:
				if mail_object is not None:
					mail_ipv4 = subscription.target_public_mail_ipv4
					mail_ipv6 = subscription.target_public_mail_ipv6
					mail_object.change_ips([
						(mail_ipv4, ip_address_to_type.get(mail_ipv4, 'shared')),
						(mail_ipv6, ip_address_to_type.get(mail_ipv6, 'shared'))
					])

		logger.debug(
			messages.LOG_MAIL_IPS_SET_TO.format(
				subscription_name=subscription.name,
				ipv4=subscription.target_public_mail_ipv4,
				ipv6=subscription.target_public_mail_ipv6
			)
		)