import logging

from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.utils import obj

logger = logging.getLogger(__name__)

class RemapDatabases(SubscriptionBackupAction):
	"""If subscription's host address for databases of particular type
	   differs from host address of databases of that type in subscription's backup,
	   change host address for these databases in subscriptions's backup.
	"""
	def get_description(self):
		return "Change database servers in backups"

	def get_failure_message(self, global_context, subscription):
		return "Failed to remap database servers for subscription '%s'" % (subscription.name)

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

	def _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		logger.debug("Change database server location for databases")
		for db in subscription_backup.all_databases:
			orig_location = new_location = obj(host=db.host, port=db.port)
			db_server = subscription.db_target_servers.get(db.dbtype)
			if db_server is not None:
				new_location = obj(host=db_server.host(), port=db_server.port())

			if new_location != orig_location:
				db.change_location(new_location)

		logger.debug("Change database server location for database users")
		for dbuser in subscription_backup.get_overall_database_users():
			if dbuser.host is None:
				continue

			orig_location = new_location = obj(host=dbuser.host, port=dbuser.port)

			db_server = subscription.db_target_servers.get(dbuser.dbtype)
			if db_server is not None:
				new_location = obj(host=db_server.host(), port=db_server.port())

			if new_location != orig_location:
				dbuser.change_location(new_location)
