from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.utils import windows_utils

logger = get_logger(__name__)


class RestoreWindowsSecurityPolicy(CommonAction):
    def get_description(self):
        return messages.ACTION_RESTORE_SECURITY_POLICY_WINDOWS

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return messages.ACTION_RESTORE_SECURITY_POLICY_WINDOWS_FAILURE

    def is_critical(self):
        """If action is critical or not

        :rtype: bool
        """
        return False

    def filter_action(self, global_context):
        return len(global_context.changed_security_policy_nodes) > 0

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        try:
            for server in global_context.changed_security_policy_nodes:
                try:
                    signature, security_policy_enabled = windows_utils.get_security_policy(server)
                    if not security_policy_enabled:
                        windows_utils.set_security_policy(server, signature, True)
                except Exception as e:
                    logger.exception()
                    logger.error(messages.FAILED_RESTORE_SECURITY_POLICY_TARGET_NODE % (server.description(), e,))
        except Exception as e:
            logger.exception()
            logger.error(messages.FAILED_RESTORE_SECURITY_POLICY_SOME_TARGET % (e,))