from parallels.core.logging import get_logger
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.utils.webmail import select_target_webmail

logger = get_logger(__name__)


class ChangeWebmail(SubscriptionBackupAction):
    def get_description(self):
        """Get short description of action as string

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

    def get_failure_message(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return messages.ACTION_CHANGE_WEBMAIL_FAILURE

    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 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
    ):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        s_mailsystem = subscription_backup.mailsystem

        remote_smarter_mail = global_context.conn.target.remote_smarter_mail_server is not None
        allowed_webmails = global_context.hosting_repository.panel.get_available_webmails()

        if s_mailsystem is not None:
            source_webmail = s_mailsystem.get_webmail()
            target_webmail = select_target_webmail(s_mailsystem.get_webmail(), allowed_webmails, remote_smarter_mail)
            if target_webmail != source_webmail:
                s_mailsystem.set_webmail(target_webmail)
                logger.fdebug(
                    messages.CHANGED_WEBMAIL_FOR_SUBSCRIPTION,
                    subscription_name=subscription.name, source_webmail=source_webmail, target_webmail=target_webmail
                )
