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
from parallels.core.utils.common import is_empty_iterator, safe_string_repr

logger = get_logger(__name__)


class SetWindowsSecurityPolicy(CommonAction):
    def get_description(self):
        return messages.ACTION_SET_SECURITY_POLICY_WINDOWS

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return messages.ACTION_SET_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 not is_empty_iterator(global_context.iter_windows_servers())

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        for server in global_context.iter_windows_servers():
            try:
                signature, security_policy_enabled = windows_utils.get_security_policy(server)
                if security_policy_enabled:
                    global_context.changed_security_policy_nodes.add(server)
                    windows_utils.set_security_policy(server, signature, False)
            except Exception as e:
                logger.exception()
                logger.error(messages.FAILED_SET_SECURITY_POLICY_WINDOWS % safe_string_repr(e))
