from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.hosting_settings.import_backups import ImportedBackups
from parallels.core.migrator_config import read_restore_hosting_settings_poll_limit, \
    read_restore_hosting_settings_poll_interval


class RestoreSubscriptionHostingSettings(SubscriptionAction):
    def get_description(self):
        return messages.RESTORE_HOSTING_SETTINGS_SUBSCRIPTION

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

    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 run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        imported_backup = ImportedBackups.get_instance().get_by_backup(subscription.server_converted_dump)
        subscription_backup_xml = imported_backup.get_domain_xml_path(subscription.name_idn)
        restore_hosting_utils = global_context.target_panel_obj.get_restore_hosting_utils(
            subscription.panel_target_server
        )
        admin_guid = global_context.hosting_repository.panel.get_administrator_guid(subscription.name)
        restore_hosting_utils.restore_hosting_settings(
            admin_guid, subscription.name, subscription_backup_xml, global_context.safe,
            restore_task_poll_limit=read_restore_hosting_settings_poll_limit(global_context.config),
            restore_task_poll_interval=read_restore_hosting_settings_poll_interval(global_context.config)
        )
