from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.reports.model.issue import Issue
from parallels.core.utils.plesk_utils import is_valid_protected_directory_name


class CheckProtectedDirNames(SubscriptionBackupAction):
    """Remove protected directories that have names which do not conform to Plesk rules
    """
    def get_description(self):
        """Get short description of action as string

        :rtype: str
        """
        return messages.ACTION_CHECK_PROTECTED_DIR_NAMES_DESCRIPTION

    def get_failure_message(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return messages.ACTION_CHECK_PROTECTED_DIR_NAMES_FAILURE

    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 get_logging_properties(self):
        """Get how action should be logged to migration tools end-user

        :rtype: parallels.core.actions.utils.logging_properties.LoggingProperties
        """
        return LoggingProperties(info_log=False)

    def _run_subscription_backup(
        self, global_context, subscription, subscription_backup
    ):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for domain in subscription_backup.iter_domains():
            for directory in list(domain.iter_protected_dirs()):
                is_valid_directory_name = is_valid_protected_directory_name(
                    subscription.web_target_server.is_windows(), directory.name
                )
                if not is_valid_directory_name:
                    subscription.add_report_issue(
                        global_context.pre_check_report,
                        'protected-directory-name-invalid', Issue.SEVERITY_WARNING,
                        messages.PROTECTED_DIRECTORY_NAME_INVALID_ISSUE.format(
                            domain=domain.name,
                            directory=directory.name
                        ),
                        messages.PROTECTED_DIRECTORY_NAME_INVALID_SOLUTION
                    )
