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 DeployDatabaseUsers(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_DATABASE_USERS

    def get_failure_message(self, global_context, subscription):
        return messages.ACTION_DEPLOY_DATABASE_USERS_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_database_users())

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for db_user in subscription.database_users:
            if global_context.hosting_repository.database_user.is_exists_by_subscription(
                subscription.name, db_user.target_name
            ):
                logger.info(messages.ACTION_DEPLOY_DATABASE_USERS_SKIP_EXISTING.format(
                    database_user_name=db_user.target_name
                ))
                continue

            target_db_server = subscription.db_target_servers.get(db_user.converted_dump.dbtype)
            if db_user.converted_dump.database_name in self._list_databases(target_db_server):
                logger.fwarn(messages.ACTION_DEPLOY_DATABASE_USERS_SKIP_NOT_REGISTERED_DATABASE.format(
                    database_user_name=db_user.target_name, database_name=db_user.converted_dump.database_name
                ))
                continue

            is_assimilate = (
                db_user.target_name == db_user.source_name and
                subscription.is_assimilate_database_user(
                    db_user.source_name,
                    db_user.dbtype
                )
            )

            if is_assimilate:
                logger.info(messages.ACTION_DEPLOY_DATABASE_USERS_ASSIMILATE_DATABASE_USER.format(
                    database_user_name=db_user.source_name,
                    subscription_name=subscription.name
                ))
            else:
                logger.info(messages.ACTION_DEPLOY_DATABASE_USERS_CREATE_DATABASE_USER.format(
                    database_user_name=db_user.target_name,
                    subscription_name=subscription.name
                ))

            try:
                global_context.hosting_repository.database_user.create_from_dump(
                    db_user.converted_dump,
                    subscription.name,
                    is_assimilate
                )
            except Exception as e:
                logger.exception()
                # place error into report and proceed to next mail account
                if is_assimilate:
                    error_message = messages.ACTION_DEPLOY_DATABASE_USERS_ASSIMILATE_DATABASE_USER_ERROR
                else:
                    error_message = messages.ACTION_DEPLOY_DATABASE_USERS_CREATE_DATABASE_USER_ERROR
                global_context.safe.fail_subscription(
                    subscription.name,
                    safe_format(
                        error_message,
                        database_user_name=db_user.target_name,
                        subscription_name=subscription.name,
                        reason=e
                    ),
                    is_critical=False,
                )
                continue

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