from collections import defaultdict

from parallels.core.actions.base.compound_action import CompoundAction


class EntryPointAction(CompoundAction):
	def __init__(self):
		super(EntryPointAction, self).__init__()
		self._shutdown_actions = defaultdict(list)

	def register_shutdown(self, action_path, shutdown_action_path):
		"""Register shutdown action, that should be always executed on exit

		For example, we set Apache restart interval, or Windows password
		policies.  When migration is finished, we should restore old Apache
		restart interval, and restore old strong Windows password policy.  We
		should do it regardless of migration status. Even if some action failed
		with exception, we should restore old settings.  So, we register such
		restoration actions as shutdown actions.

		Arguments:
		- action_path - path to "set up" action, for example that one that
		  changes Apache restart interval to high value
		- shutdown_action_path - path to "shut down" action, for example that
		  one that changes Apache restart interval back to the initial value

		Note that both set up and shut down actions must be registered in
		workflow.
		"""
		self._shutdown_actions[action_path].append(shutdown_action_path)

	def register_overall_shutdown(self, shutdown_action_path):
		"""Register overall shutdown action, that should be always executed on exit

		Overall shutdown action is executed always, no difference which other actions
		were executed and what was their result.

		Arguments:
		- shutdown_action_path - path to "shut down" action, for example that
		  one that closes all connections, or removes temporary SSH keys from
		  nodes involved in migration process
		"""
		self._shutdown_actions[None].append(shutdown_action_path)

	def get_shutdown_actions(self):
		"""Get shutdown actions, that should be always executed on exit

		Returns dictionary {set_up_action_path: [shut_down_action_paths]}
		set_up_action_path could be None - that means overall shutdown action,
		which should be executed always, no difference which other actions
		were executed and what was their result.
		"""
		return dict(self._shutdown_actions)