import logging
import os
from parallels.common import MigrationError
from parallels.common.actions.base.common_action import CommonAction
from parallels.shm_move_webspaces.move_list import read_move_list
from parallels.utils import format_multiline_list

logger = logging.getLogger(__name__)


class LoadMoveListAction(CommonAction):
	def run(self, global_context):
		"""
		:type global_context: parallels.common.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(u"Failed to read move list:\n%s\nPlease fix the move list file '%s' and restart moving tools." % (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 u'Load list of webspaces which should be moved and store it into global context'

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return u'Failed to load list of webspaces which should be moved and store it into global context'

	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(
					u"Move list file does not exists. Please put correct move list file to '%s', or specify correct path to move list file with --move-list-file command-line option and restart moving tools." % move_list_file
				)
			logger.info(u"Move list from '%s' is used", move_list_file)
			return move_list_file
		else:
			raise MigrationError(u"Required command-line option --move-list-file is not specified")

