from parallels.core.logging import get_logger
from parallels.core.migrator_config import PhysicalServerConfig
from parallels.plesk.source.custom import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.plesk.hosting_description.converter_to_dump import (
    HostingDescriptionToPleskDumpConverter, read_hosting_description_file
)
from parallels.plesk.hosting_description.converter_to_dump import DEFAULT_SOURCE_IP

logger = get_logger(__name__)


class CreateDumpFromHostingDescription(CommonAction):
    """Create Plesk configuration dump file (raw) out of hosting description file"""

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_CREATE_DUMP_FAILURE

    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_CREATE_DUMP_DESCRIPTION

    def run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.custom.global_context.CustomPanelGlobalMigrationContext
        :rtype: None
        """
        conn = global_context.conn
        """:type conn: parallels.plesk.source.custom.connections.MigratorConnections"""
        for hosting_description_config in conn.iter_hosting_description_configs():
            is_windows = global_context.conn.target.is_windows
            dump_filename = global_context.session_files.get_raw_dump_filename(hosting_description_config.source_id)
            source = global_context.conn.get_source_by_id(hosting_description_config.source_id)
            source_ip = source.ip() if isinstance(source.config, PhysicalServerConfig) else DEFAULT_SOURCE_IP
            logger.info(messages.LOG_CREATE_DUMP, hosting_description_config.source_id)
            target_plesk_version = global_context.conn.target.plesk_server.get_plesk_version()
            dump_creator = HostingDescriptionToPleskDumpConverter(
                data=read_hosting_description_file(hosting_description_config),
                target_dump_file=dump_filename,
                target_plesk_version=target_plesk_version,
                database_servers=list(global_context.conn.iter_database_servers()),
                is_windows=is_windows,
                source_ip=source_ip,
                mail_server_ips={server.source_id: server.ip() for server in conn.get_external_mail_servers()}
            )
            dump_creator.write_dump()
