from parallels.core.logging import get_logger
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.utils.common import obj

logger = get_logger(__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 messages.CHANGE_DATABASE_SERVERS_IN_BACKUPS

    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.FAILED_REMAP_DATABASE_SERVERS_FOR_SUBSCRIPTION % subscription.name

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

    def _run_subscription_backup(
        self, global_context, subscription, subscription_dump
    ):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type subscription_dump: parallels.core.dump.data_model.Subscription
        """
        logger.debug(messages.CHANGE_DATABASE_SERVER_LOCATION_FOR_DATABASES)
        for db in subscription_dump.iter_all_databases():
            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())
                db.change_location(new_location)
            else:
                subscription_dump.remove_database(db)

        logger.debug(messages.CHANGE_DATABASE_SERVER_LOCATION_FOR_DATABASE)
        for dbuser in subscription_dump.iter_overall_database_users():
            if dbuser.host is None:
                continue

            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())
                dbuser.change_location(new_location)
            else:
                subscription_dump.remove_database_user(dbuser)
