import logging
from parallels.core.actions.base.common_action import CommonAction
from parallels.core import messages
from parallels.ppa.importer import PPAClientAndSubscriptionImporter

logger = logging.getLogger(__name__)


class ImportClientsAndSubscriptions(CommonAction):
	def get_description(self):
		return messages.IMPORT_CLIENTS_AND_SUBSCRIPTIONS

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_IMPORT_CLIENTS_AND_SUBSCRIPTIONS

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		import_api = global_context.target_panel_obj.get_import_api(global_context)
		importer = PPAClientAndSubscriptionImporter(import_api, global_context.conn.target, global_context.safe)
		importer.import_clients_and_subscriptions(
			global_context.target_model, global_context.target_existing_objects,
			clean_up_vhost_skeleton=True,
			subscription_source_mail_ips=self._get_subscription_source_mail_ips(global_context)
		)
		# clear public IP addresses cache, as new IP addresses may be added to Plesk in case of dedicated IPs
		global_context.conn.target.plesk_server.get_all_ips.clear()

	@staticmethod
	def _get_subscription_source_mail_ips(global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		mail_ips = dict()

		for subscription in global_context.iter_all_subscriptions():
			mail_ips[subscription.name] = subscription.source_mail_ip

		return mail_ips