from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.plesk.utils.xml_rpc.plesk import operator as plesk_ops


class ResetHostingForSubscriptionWithoutHosting(SubscriptionAction):
    """When subscription is created, for technical reasons now it has physical hosting turned on. We disable it here.

    If domains has another type of hosting (not physical) it will be switched during
    restoration from backup. However, if domains has no hosting then Plesk leaves physical
    hosting after restoration from backup.
    Thus it is needed to manually switch off hosting for such subscriptions.
    """
    def get_description(self):
        return messages.RESET_HOSTING_FOR_SUBSCRIPTIONS_WITHOUT_HOSTING

    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 filter_subscription(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return subscription.converted_dump.hosting_type == 'none'

    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_RESET_HOSTING_FOR_SUBSCRIPTIONS_WITHOUT % subscription.name

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        with restore_hosting_settings_lock:
            results = subscription.panel_target_server.plesk_api().send(plesk_ops.SubscriptionOperator.Set(
                filter=plesk_ops.SubscriptionOperator.FilterByName([subscription.name]),
                hosting=plesk_ops.SubscriptionHostingNone(),
                limits=None,
            ), plesk_disable_provisioning='true')
        for result in results:
            result.check()
