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):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		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
	):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		logger.debug("Change database server location for databases")
		for db in subscription_backup.all_databases:
			db_port = db.port if db.port != 0 and db.port != 1433 else None
			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

			dbuser_port = dbuser.port if dbuser.port != 0 and dbuser.port != 1433 else None
			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)