from parallels.core import messages
from parallels.core import safe_format
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.converter.database import DatabaseConflictingObjectDescription, SourceDatabaseConflictingObject
from parallels.core.logging import get_logger
from parallels.core.reports.model.issue import Issue
from parallels.core.utils.database_utils import db_type_pretty_name
from parallels.core.utils.name_conflicts import resolve_conflicts

logger = get_logger(__name__)


class ResolveDatabaseNameConflicts(CommonAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str
        """
        return messages.ACTION_RESOLVE_DATABASE_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_NAME_CONFLICTS_FAILURE

    def get_logging_properties(self):
        """Get how action should be logged to migration tools end-user

        :rtype: parallels.core.actions.utils.logging_properties.LoggingProperties
        """
        return LoggingProperties(info_log=False)

    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):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        conflicting_object_description = DatabaseConflictingObjectDescription(global_context)
        resolve_conflicts(
            global_context.name_mapping, conflicting_object_description, merge_subscriptions=True
        )

        for subscription in global_context.iter_all_subscriptions():
            for database in subscription.databases:
                new_name = global_context.name_mapping.get_new_name(
                    conflicting_object_description.get_type_id(),
                    SourceDatabaseConflictingObject(subscription, database.raw_dump)
                )
                if new_name != database.source_name:
                    database.converted_dump.set_name(new_name)
                    subscription.add_report_issue(
                        global_context.pre_check_report,
                        'database-with-such-name-already-exists', Issue.SEVERITY_WARNING,
                        safe_format(
                            messages.DATABASE_EXISTS_ISSUE,
                            db_name=database.source_name, db_type=db_type_pretty_name(database.dbtype),
                            new_db_name=new_name
                        )
                    )
