from parallels.core.logging import get_logger
from parallels.core.utils.name_conflicts import resolve_conflicts
from parallels.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.site_migration import SiteMigrationAction
from parallels.plesk.source.web.conflicts.database_user import SourceDatabaseUserConflictingObject, \
    DatabaseUserConflictingObjectDescription

logger = get_logger(__name__)


class ResolveDatabaseUserNameConflicts(SiteMigrationAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str
        """
        return messages.ACTION_RESOLVE_DATABASE_USER_NAME_CONFLICTS_DESCRIPTION

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return messages.ACTION_RESOLVE_DATABASE_USER_NAME_CONFLICTS_FAILURE

    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 run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :rtype: None
        """
        conflicting_object_description = DatabaseUserConflictingObjectDescription(global_context)
        resolve_conflicts(
            global_context.name_mapping, conflicting_object_description, merge_subscriptions=True
        )
        for database_user in global_context.list_all_migrated_database_users():
            new_name = global_context.name_mapping.get_new_name(
                conflicting_object_description.get_type_id(),
                SourceDatabaseUserConflictingObject(database_user)
            )
            if new_name != database_user.source_username:
                database_user.set_target_username(new_name)
