import os
import shutil

from parallels.core import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.logging import get_logger
from parallels.core.utils.common import is_run_on_windows
from parallels.core.utils.tar_utils import tar_directory
from parallels.core.utils.zip_utils import zip_directory

logger = get_logger(__name__)


class Pack(CommonAction):
    """Pack unpacked raw backups from unpacked directory to archives"""

    def get_description(self):
        return messages.ACTION_PACK_BACKUPS

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

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        for plesk_id in global_context.source_servers:
            session_files = global_context.session_files
            self._pack_plesk_backup(global_context, session_files.get_raw_dump_filename(plesk_id))
            self._pack_plesk_backup(global_context, session_files.get_converted_dump_filename(plesk_id))

    @staticmethod
    def _pack_plesk_backup(global_context, backup_filename):
        """Pack single Plesk backup into archive

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        extract_dirname = global_context.session_files.get_file_path(
            'unpacked', os.path.basename(backup_filename)
        )
        if not os.path.exists(extract_dirname):
            return

        if os.path.exists(backup_filename):
            shutil.move(backup_filename, "%s.orig" % backup_filename)

        logger.finfo(messages.PACK_BACKUP, directory=extract_dirname, backup=backup_filename)

        if is_run_on_windows():
            zip_directory(extract_dirname, backup_filename)
        else:
            tar_directory(extract_dirname, backup_filename)