from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.utils.common import format_table
from parallels.core.utils.paths.converters.source import SourceWebPathConverter
from parallels.core.utils.paths.converters.target import TargetWebPathConverter

logger = get_logger(__name__)


class ListFiles(CommonAction):
    """Base class to copy web content for Unix servers"""

    def get_description(self):
        """
        :rtype: str | unicode
        """
        return messages.LIST_FILES_TO_COPY_ACTION_DESCRIPTION

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return messages.LIST_FILES_TO_COPY_ACTION_FAILURE

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        table = [['Subscription', 'From', 'To']]
        for subscription in global_context.iter_all_subscriptions():
            if not global_context.migrator.web_files.need_to_copy_files(global_context, subscription):
                continue

            target_server = subscription.web_target_server
            for item in global_context.migrator.web_files.list_files_to_copy(global_context, subscription):
                source_server = global_context.migrator.get_domain_source_web_server(subscription, item.domain_name)
                vhosts_dir = global_context.migrator.web_files.get_source_vhosts_dir(global_context, source_server)
                source_path = SourceWebPathConverter(vhosts_dir).expand(item.source_path, source_server)
                target_path = TargetWebPathConverter().expand(item.target_path, target_server)
                table.append([subscription.name, source_path, target_path])

        logger.info(messages.FILES_TO_COPY + "\n" + format_table(table))
