from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.dump.entity.password import password_is_empty


class NoPasswordMailuserDisableCPAccess(SubscriptionBackupAction):
    """For mailboxes that have control panel access, but have no password, disable control panel access

    This is necessary for PMM deployer not to fail, because password is required by Plesk utilities
    when creating mail user with control panel access. If you have an auxiliary user which has non-empty password
    and login which is the same as mailuser, it will still be able to login, so this case is ok.

    Pay attention in subscription reassign scenario, when subscription was owned by customer, but during
    migration is assigned to administrator. In that case auxiliary user will not be migrated, and so
    there will be no access to the target control panel with mailuser's login.
    """
    def get_description(self):
        """Get short description of action as string

        :rtype: str
        """
        return messages.ACTION_DISABLE_CP_ACCESS_FOR_NO_PASSWORD_MAILUSER

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return messages.FAILED_DISABLE_CP_ACCESS_FOR_NO_PASSWORD_MAILUSER

    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. This action is not critical, as the only
        impact if we don't remove CP access flag for mailusers without password is an extra error
        message from PMM deployer

        :rtype: bool
        """
        return False

    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 _run_subscription_backup(
        self, global_context, subscription, subscription_backup
    ):
        """Run action on single subscription on provided backup

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for mailbox in subscription_backup.iter_mailboxes():
            if mailbox.cp_access and password_is_empty(mailbox.password):
                mailbox.cp_access = False
