import os

from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core import MigrationError
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.ip_mapping import IPMappingReader, IPMapping
from parallels.core.utils.common import open_no_inherit

logger = get_logger(__name__)


class ReadIPMapping(CommonAction):
    def get_description(self):
        return messages.ACTION_READ_IP_MAPPING

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

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """

        ip_mapping_file = None
        if global_context.options.ip_mapping_file is None:
            default_ip_mapping_file = global_context.session_files.get_path_to_default_ip_mapping_file()
            if os.path.exists(default_ip_mapping_file):
                ip_mapping_file = default_ip_mapping_file
        else:
            ip_mapping_file = global_context.options.ip_mapping_file

        if ip_mapping_file is None:
            global_context.ip_mapping = IPMapping()  # empty IP mapping
        else:
            if not os.path.exists(ip_mapping_file):
                raise MigrationError(
                    messages.ACTION_READ_IP_MAPPING_IP_MAPPING_FILE_NOT_EXIST.format(ip_mapping_file=ip_mapping_file)
                )
            all_target_ips = {
                ip.ip_address
                for ip in global_context.conn.target.plesk_server.get_all_ips()
            }
            logger.info(messages.ACTION_READ_IP_MAPPING_READ_IP_MAPPING_FILE.format(ip_mapping_file=ip_mapping_file))
            with open_no_inherit(ip_mapping_file, 'rb') as fp:
                global_context.ip_mapping = IPMappingReader(all_target_ips).read(fp)

    def get_logging_properties(self):
        """Get how action should be logged to migration tools end-user"""
        return LoggingProperties(info_log=True, compound=False)
