from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
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 DeployPanelUsersSubscription(SubscriptionAction):
    def get_description(self):
        """Get short description of action as string

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

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: str | unicode
        """
        return messages.FAILED_TO_RESTORE_SUBSCRIPTION_AUX_USERS

    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):
        """Check if we should run this action on given subscription or not

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: bool
        """
        return len(self._list_panel_users_to_create(global_context, subscription.name)) > 0

    def run(self, global_context, subscription):
        """Perform creation of subdomains for given subscription on target Plesk

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

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

