from parallels.core import messages
import logging
from parallels.core.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 messages.ACTION_RESTORE_AUX_USER_ROLES

	def get_failure_message(self, global_context):
		return messages.FAILED_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,
				messages.FAILED_CREATE_AUXILIARY_USER_ROLE_PLESK_2):
			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) is not None:
			logger.debug(messages.SKIPPED_CREATING_AN_EXISTING_ROLE + role.name)
			return True
		elif role.name in self.default_roles:
			logger.debug(messages.SKIPPED_CREATING_DEFAULT_ROLE + role.name)
			return True
		else:
			return False

	@staticmethod
	def _get_existing_role(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
