from parallels.core import messages
import os
from parallels.core import MigrationError
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.ip_mapping import IPMappingReader, IPMapping


class ReadIPMapping(CommonAction):
	def get_description(self):
		return "Read IP mapping file"

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

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		if global_context.options.ip_mapping_file is None:
			global_context.ip_mapping = IPMapping()  # empty IP mapping
		else:
			if not os.path.exists(global_context.options.ip_mapping_file):
				raise MigrationError(
					messages.IP_MAPPING_FILE_S_DOES_NOT % (
						global_context.options.ip_mapping_file
					)
				)
			all_target_ips = {
				ip.ip_address
				for ip in global_context.conn.target.plesk_server.get_all_ips(global_context)
			}
			with open(global_context.options.ip_mapping_file, 'rb') as fp:
				global_context.ip_mapping = IPMappingReader(all_target_ips).read(fp)

	def get_logging_properties(self):
		"""Get how action should be logged to migration tools end-user"""
		return LoggingProperties(info_log=True, compound=False)
