import logging
from parallels.common.actions.base.common_action import CommonAction

logger = logging.getLogger(__name__)


class RestoreAuxUserRoles(CommonAction):
	"""Create user roles on the target panel."""
	# default roles, that Plesk creates automatically
	default_roles = ('Application User', 'WebMaster')

	def get_description(self):
		return "Restore auxuser roles"

	def get_failure_message(self, global_context):
		return "Failed to restore auxuser roles"

	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 False

	def run(self, global_context):
		model = global_context.target_model.model
		for _, target_client in model.clients.items():
			for role in target_client.auxiliary_user_roles:
				self._create_role(role, target_client, global_context)

	def _create_role(self, role, client, context):
		if self._should_skip_role_creation(role, client, context):
			return
		with context.safe.try_auxiliary_user_role(
				client.login, role.name,
				u"Failed to create auxiliary user role with Plesk API."):
			context.import_api.create_auxuser_role(role, client)

	def _should_skip_role_creation(self, role, client, context):
		if self._get_existing_role(role, client, context) != None:
			logger.debug("Skipped creating an existing role " + role.name)
			return True
		elif role.name in self.default_roles:
			logger.debug("Skipped creating a default role " + role.name)
			return True
		else:
			return False

	def _get_existing_role(self, role, client, context):
		"""Return a role object that exists on target panel."""
		existing_roles = context.target_existing_objects.auxiliary_user_roles
		if (client.login, role.name) in existing_roles:
			return existing_roles[(client.login, role.name)]
		else:
			return None
