from parallels.shm_web_sn.source.shm_web_sn import messages
import logging
import os
from parallels.core import MigrationError
from parallels.core.actions.base.common_action import CommonAction
from parallels.shm_web_sn.source.shm_web_sn.move_list import read_move_list
from parallels.core.utils.common import format_multiline_list

logger = logging.getLogger(__name__)


class LoadMoveListAction(CommonAction):
	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		move_list_filename = self._get_move_list_filename(global_context.options)
		with open(move_list_filename, 'r') as f:
			move_list, errors = read_move_list(f)
			if len(errors) != 0:
				raise MigrationError(messages.FAILED_TO_READ_MOVE_LIST % (
					format_multiline_list(errors), move_list_filename)
				)
			global_context.webspace_name = move_list.name
			global_context.webspace_ipv4 = move_list.web_ip_v4
			global_context.webspace_ipv4_type = move_list.web_ip_v4_type
			global_context.webspace_ipv6 = move_list.web_ip_v6
			global_context.webspace_ipv6_type = move_list.web_ip_v6_type

	def get_description(self):
		return messages.LOAD_LIST_OF_WEBSPACES

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

	def _get_move_list_filename(self, options):
		if options.migration_list_file is not None:
			move_list_file = options.migration_list_file
			if not os.path.exists(move_list_file):
				raise MigrationError(
					messages.MOVE_LIST_FILE_DOES_NOT_EXISTS % move_list_file
				)
			logger.info(messages.MOVE_LIST_USED, move_list_file)
			return move_list_file
		else:
			raise MigrationError(messages.MOVE_LIST_NOT_SPECIFIED)