from parallels.core.logging import get_logger
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.plesk.source.cpanel import messages

logger = get_logger(__name__)


class FixSpamassassinPatterns(SubscriptionBackupAction):
    """Fix SpamAssassin blacklist and whitelist items that do not conform to Plesk rules"""

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

        :rtype: str
        """
        return messages.ACTION_TITLE_FIX_SPAMASSASSIN_PATTERNS

    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_FAILURE_FIX_SPAMASSASSIN_PATTERNS

    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
        """
        for mailuser in subscription_backup.iter_mailboxes():
            for pattern in mailuser.iter_spamassassin_patterns():
                parts = pattern.address.split('@', 1)
                if len(parts) == 1:
                    # Pattern consists of domain name only, considering that all mailboxes of domain
                    # should be affected by the rule
                    old_pattern = pattern.address
                    pattern.address = '*@%s' % parts[0]
                    logger.debug(messages.LOG_CHANGED_SPAMASSASSIN_PATTERN.format(
                        old_pattern=old_pattern, new_pattern=pattern.address, mailbox_name=mailuser.name
                    ))
                else:
                    if parts[0] == '':
                        # Mailname part is empty, considering that all mailboxes of domain
                        # should be affected by the rule
                        old_pattern = pattern.address
                        pattern.address = '*@%s' % parts[1]
                        logger.debug(messages.LOG_CHANGED_SPAMASSASSIN_PATTERN.format(
                            old_pattern=old_pattern, new_pattern=pattern.address, mailbox_name=mailuser.name
                        ))
