from parallels.core import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.deploy.panel_users_utils import iter_panel_users_to_create, create_panel_user
from parallels.core.logging import get_logger
from parallels.core.utils.common import cached

logger = get_logger(__name__)


class DeployPanelUsersOverall(CommonAction):
    """Deploy auxiliary users which are not assigned to any subscription"""

    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_RESTORE_OVERALL_AUX_USERS

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.FAILED_TO_RESTORE_OVERALL_AUX_USERS

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

        If action is critical and it failed, migration tool completely stops.
        Otherwise it proceeds to the next steps of migrations.

        :rtype: bool
        """
        return False

    def filter_action(self, global_context):
        """Check whether we should run this action or not. By default True - action should be executed.

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: bool
        """
        return len(self._list_panel_users_to_create(global_context)) > 0

    def run(self, global_context):
        """Run action

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: None
        """
        for panel_user, owner in self._list_panel_users_to_create(global_context):
            create_panel_user(panel_user, owner, global_context)

    @staticmethod
    @cached
    def _list_panel_users_to_create(global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return list(iter_panel_users_to_create(global_context, subscription_name=None))
