from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties \
	import LoggingProperties
from parallels.core.checking import Problem

class CheckServicePlanAccordance(SubscriptionBackupAction):
	def get_description(self):
		return messages.ACTION_CHECK_SERVICE_PLAN_ACCORDANCE_DESCRIPTION

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.ACTION_CHECK_SERVICE_PLAN_ACCORDANCE_FAILURE % subscription.name

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

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

		:rtype: bool
		"""
		return False

	def get_logging_properties(self):
		return LoggingProperties(info_log=False)

	def _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		:type subscription_backup: parallels.core.dump.data_model.Subscription
		"""

		is_custom = subscription.model.plan_name is None
		is_locked = subscription.raw_dump.locked
		if is_custom or is_locked:
			return

		api = global_context.target_panel_obj.get_import_api(global_context)
		owner_username = None if subscription.model_reseller is None else subscription.model_reseller.login
		service_template_details = api.get_service_template_details_by_name(subscription.model.plan_name, owner_username)

		if subscription_backup.get_phosting_sysuser_name() is not None \
				and subscription.raw_dump.plan is not None \
				and subscription.raw_dump.plan.properties.get('shell', '/bin/false') != '/bin/false' \
				and service_template_details is not None and service_template_details.shell == '/bin/false':
					subscription.add_report_issue(
						global_context.pre_check_report,
						Problem(
							'service-plan-accordance-issue', Problem.WARNING,
							messages.SERVICE_PLAN_ACCORDANCE_ISSUE.format(
								subscription_name=subscription.name,
								plan_name=subscription.model.plan_name
							)
						),
						messages.SERVICE_PLAN_ACCORDANCE_SOLUTION.format(
							subscription_name=subscription.name,
							plan_name=subscription.model.plan_name
						)
					)