from parallels.core.logging import get_logger
from parallels.core.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.plesk.source.plesk import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.utils import subscription_filter

logger = get_logger(__name__)


class ResetPermissions(SubscriptionAction):
    """Reset file permissions on Windows like Plesk restore does"""
    
    def get_description(self):
        """Get short description of action as string

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

    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
        """
        return messages.ACTION_RESET_PERMISSIONS_FAILURE % 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 filter_subscription(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: bool
        """
        return (
            subscription_filter.windows_with_virtual_hosting(subscription) and
            # Check that the action is already executed. This action is executed a long time
            # for subscriptions with huge count of folders. So we skip it repeat runs.
            subscription_filter.reset_permissions(subscription, global_context)
        )

    def run(self, global_context, subscription):
        """
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        with restore_hosting_settings_lock:
            global_context.hosting_repository.subscription.update_security(subscription.name)
