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

logger = get_logger(__name__)


class ChangeHostingSubscriptionWebIPs(SubscriptionBackupAction):
    """Change web IPs according to subscription's hosting addresses for subscription with virtual hosting"""

    def get_description(self):
        return messages.CHANGE_VHOSTING_SUBSCRIPTION_WEB_IP_IN_BACKUP

    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.FAILED_TO_CHANGE_VHOSTING_SUBSCRIPTION_WEB_IP_IN_BACKUP

    def get_logging_properties(self):
        return LoggingProperties(info_log=False)

    def _filter_subscription_backup(self, global_context, subscription, subscription_backup):
        return subscription_backup.hosting_type != 'none'

    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
        """
        all_target_ips = subscription.panel_target_server.get_all_ips()
        ip_address_to_type = {ip.ip_address: ip.ip_type for ip in all_target_ips}
        (v4, v6) = (
            subscription.target_web_ip,
            subscription.target_web_ipv6
        )
        subscription_backup.change_web_ips([
            (v4, ip_address_to_type.get(v4, 'shared')),
            (v6, ip_address_to_type.get(v6, 'shared'))
        ])

        logger.debug(
            messages.LOG_WEB_IPS_SET_TO.format(
                subscription_name=subscription.name,
                ipv4=v4,
                ipv6=v6
            )
        )