import os
import shutil

from parallels.core import messages

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.migration_list.utils import get_migration_list_file_location
from parallels.core.actions.utils.logging_properties \
    import LoggingProperties


class SaveConverted(CommonAction):
    def __init__(self, subscription_backup):
        """Class constructor

        Arguments:
        - subscription_backup - object that can retrieve subscription backup
        object for each subscription, list of servers with backups
        """
        self._subscription_backup = subscription_backup

    def get_description(self):
        return messages.ACTION_SAVE_CONVERTED_BACKUPS

    def get_failure_message(self, global_context):
        return messages.FAILED_SAVE_CONVERTED_BACKUP_FILE

    def get_logging_properties(self):
        return LoggingProperties(info_log=False)

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        backup_ids = self._subscription_backup.get_backup_ids(global_context)
        for backup_id in backup_ids:
            # overwrite converted backup file with data from converted backup object
            backup = global_context.load_converted_dump(backup_id)
            backup.save_to_the_same_file()

            migr_list_file = get_migration_list_file_location(global_context)
            cache_migration_list = global_context.session_files.get_converted_dump_migration_list_filename(backup_id)

            if migr_list_file is not None and os.path.exists(migr_list_file):
                shutil.copy2(migr_list_file, cache_migration_list)
