from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.common.checking import Problem
from parallels.common.utils.plesk_utils import get_database_subscription


class CheckDatabaseConflicts(SubscriptionBackupAction):
	def get_description(self):
		return "Check database conflicts, when database already exists but owned by another subscription"

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return "Failed to check database conflicts for subscription '%s'" % 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.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		for db in subscription_backup.all_databases:
			db_server = subscription.db_target_servers.get(db.dbtype)

			if db_server is None:
				continue

			target_database_subscription = get_database_subscription(
				subscription.panel_target_server,
				db.name, db.dbtype,
				db_server.host()
			)

			if target_database_subscription is None:
				continue
			if target_database_subscription == subscription.name:
				continue

			subscription_backup.remove_database(db)
			subscription.add_report_issue(
				global_context.pre_check_report,
				Problem(
					'database-with-such-name-already-exists', Problem.ERROR,
					u"Database '%s' of type '%s' of subscription can not be migrated: database with such name already "
					u"exists on target server and is owned by another subscription '%s'" % (
						db.name,  db.dbtype, target_database_subscription
					)
				),
				u"Rename database either on source or on target to make database name unique.\n"
				u"Other possible way is to migrate subscription to another database server\n"
				u"(attach new external database server, "
				u"specify it in service plan the subscription is assigned to)"
			)
