from parallels.core import safe_format
from parallels.core.hosting_repository.database import CreateDatabaseEntity
from parallels.core.utils.database_server_type import DatabaseServerType
from parallels.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.database import DatabaseAction


class DeployDatabases(DatabaseAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_DEPLOY_DATABASE_DESCRIPTION

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_DEPLOY_DATABASE_FAILURE

    def is_critical(self):
        """If action is critical or not

        If action is critical and it failed, migration tool completely stops.
        Otherwise it proceeds to the next steps of migrations.

        :rtype: bool
        """
        return False

    def get_failure_message_for_database(self, global_context, database):
        """Get message for situation when action failed for specific database

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type database: parallels.plesk.source.web.migrated_database.WebMigratedDatabase
        :rtype: str | unicode | None
        """
        return safe_format(
            messages.ACTION_DEPLOY_DATABASE_FAILURE_FOR_DATABASE,
            name=database.target_name
        )

    def run_for_database(self, global_context, database):
        """Run action for single migrated database

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type database: parallels.plesk.source.web.migrated_database.WebMigratedDatabase
        :rtype: list[parallels.core.reports.model.issue.Issue] | None
        """
        if global_context.hosting_repository.database.is_exists_by_subscription(
            database.target_subscription_name, database.target_name
        ):
            return

        global_context.hosting_repository.database.create(
            CreateDatabaseEntity(
                database.target_name,
                DatabaseServerType.MYSQL,
                database.target_server.host(),
                database.target_server.port()
            ),
            database.target_subscription_name
        )
