import os

from parallels.core import messages
from parallels.core.actions.base.compound_action import CompoundAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.logging import get_logger
from parallels.core.utils.backup_adapter import SubscriptionBackup
from parallels.core.utils.migrator_utils import is_cache_enabled_and_valid

logger = get_logger(__name__)


class ConvertHostingSettingsAction(CompoundAction):
    def __init__(self):
        """Class constructor"""
        super(ConvertHostingSettingsAction, self).__init__(
            description=messages.CONVERT_HOSTING_SETTINGS_TARGET_PANEL_FORMAT,
            # run by layer for better logging, no sense to run by subscription
            run_by_subscription=False,
            logging_properties=LoggingProperties(compound=False)
        )

    def clone_without_children(self):
        return ConvertHostingSettingsAction()

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

        Arguments:
        - global_context - registry with different objects that reused among different actions

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: bool
        """
        backup_ids = SubscriptionBackup().get_backup_ids(global_context)
        for backup_id in backup_ids:
            migration_list = global_context.session_files.get_converted_dump_migration_list_filename(backup_id)
            if not is_cache_enabled_and_valid(global_context, migration_list):
                # Execute all convert hosting actions even if single converted dump is outdated
                return True

            backup_file = global_context.session_files.get_converted_dump_filename(backup_id)
            if not os.path.exists(backup_file):
                # Execute all convert hosting actions if single converted dump does not exists
                return True

        # Do not execute convert hosting actions if all converted backups exists and valid (comply to the current
        # migration list)
        logger.info(messages.USE_CONVERTED_DUMPS_FROM_CACHE)
        return False
