from parallels.core.logging import get_logger
from parallels.core.utils.common import is_empty_iterator, safe_format, cached
from parallels.core.utils.database_utils import list_databases
from parallels.plesk import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction

logger = get_logger(__name__)


class DeployDatabases(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_DATABASES

    def get_failure_message(self, global_context, subscription):
        return messages.ACTION_DEPLOY_DATABASES_FAILED.format(subscription_name=subscription.name)

    def is_critical(self):
        return False

    def filter_subscription(self, global_context, subscription):
        return not is_empty_iterator(subscription.converted_dump.iter_all_databases())

    def run(self, global_context, subscription):
        """Perform creation of databases for given subscription on target Plesk

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for database in subscription.databases:
            if global_context.hosting_repository.database.is_exists_by_subscription(
                subscription.name, database.target_name
            ):
                logger.info(messages.ACTION_DEPLOY_DATABASES_SKIP_EXISTING.format(
                    database_name=database.target_name
                ))
                continue

            target_db_server = subscription.db_target_servers.get(database.dbtype)
            if database.target_name in self._list_databases(target_db_server):
                logger.fwarn(messages.ACTION_DEPLOY_DATABASES_SKIP_NOT_REGISTERED.format(
                    database_name=database.target_name
                ))
                continue

            is_assimilate = (
                database.source_name == database.target_name and
                subscription.is_assimilate_database(database.source_name, database.dbtype)
            )

            if is_assimilate:
                logger.info(messages.ACTION_DEPLOY_DATABASES_ASSIMILATE_DATABASE.format(
                    database_name=database.source_name,
                    subscription_name=subscription.name
                ))
            else:
                logger.info(messages.ACTION_DEPLOY_DATABASES_CREATE_DATABASE.format(
                    database_name=database.target_name,
                    subscription_name=subscription.name
                ))
            try:
                global_context.hosting_repository.database.create_from_dump(
                    database.converted_dump,
                    subscription.name,
                    is_assimilate
                )
            except Exception as e:
                logger.exception()
                # place error into report and proceed to next database
                if is_assimilate:
                    error_message = messages.ACTION_DEPLOY_DATABASES_ASSIMILATE_DATABASE_ERROR
                else:
                    error_message = messages.ACTION_DEPLOY_DATABASES_CREATE_DATABASE_ERROR
                global_context.safe.fail_subscription(
                    subscription.name,
                    safe_format(
                        error_message,
                        database_name=database.target_name,
                        subscription_name=subscription.name,
                        reason=e
                    ),
                    is_critical=False,
                )
                continue

    @staticmethod
    @cached
    def _list_databases(database_server):
        return list_databases(database_server)
