import os
import logging

from parallels.core import MigrationError
from parallels.core.actions.base.common_action import CommonAction
from parallels.shcm_web_sn.source.shcm_web_sn.actions.migration_list.move_list import read_move_list, MoveList
from parallels.core.utils.common import format_multiline_list
from parallels.shcm_web_sn.source.shcm_web_sn import messages

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 = MoveList()
			errors = read_move_list(f, move_list)
			if len(errors) != 0:
				raise MigrationError(
					messages.FAILED_TO_READ_MOVE_LIST.format(
						errors=format_multiline_list(errors), path=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
			global_context.webspace_src_ctx = move_list.src_ctx
			global_context.webspace_dst_ctx = move_list.dst_ctx

	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.format(path=move_list_file))

			logger.info(messages.MOVE_LIST_USED.format(path=move_list_file))
			return move_list_file
		else:
			raise MigrationError(messages.MOVE_LIST_NOT_SPECIFIED)
