import sys

from parallels.core import messages
from parallels.core.registry import Registry
from parallels.core.run_command import WindowsAgentRunner
from parallels.core.actions.base.common_action import CommonAction
from parallels.core import MigrationError

import logging

logger = logging.getLogger(__name__)


class CallbackAction(CommonAction):
	def get_description(self):
		return messages.ACTION_CALLBACK

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

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed, migration tool won't run the next operations.

		:rtype: bool
		"""
		return True

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		registry = Registry.get_instance()
		source_servers_info = global_context.get_source_servers_info()
		if len(source_servers_info) == 0:
			raise MigrationError(messages.NO_SOURCE_SERVERS_FOR_CALLBACK)
		runner = WindowsAgentRunner(
			source_servers_info[0].settings,
			registry.get_context().migrator_server
		)
		runner.callback(ur'"{python_path}" "{execution_path}" "{var_dir}" {command} "{config}"'.format(
			python_path=sys.executable,
			execution_path=registry.get_execution_path(),
			var_dir=registry.get_var_dir(),
			command=global_context.options.command,
			config=registry.get_config_path()
		))