from parallels.core.migrated_subscription import MigratedSubscription
from parallels.core.registry import Registry
from parallels.core.utils.common import cached
from parallels.plesk.source.helm3 import helm_constants
from parallels.plesk.source.helm3.helm3_agent import NoServiceIpHelmDatabase


class Helm3MigratedSubscription(MigratedSubscription):
    @property
    def mail_source_server(self):
        """Get source mail server for subscription (SourceServer object)"""
        global_context = Registry().get_instance().get_context()
        if self.source_mail_ip is not None:
            return global_context.conn.helm3.get_source_server_by_ip(self.source_mail_ip)
        else:
            return None

    @property
    @cached
    def source_mail_ip(self):
        """Get IPv4 address on which mail service of subscription works on the source panel

        :rtype: str | unicode | None
        """
        # Request source Helm 3 server, as IP address is not presented in dump file
        global_context = Registry().get_instance().get_context()
        domain_name = self._get_first_real_domain_with_mail()
        if domain_name is None:
            return None
        try:
            return global_context.migrator.get_service_ip(helm_constants.MAIL_SERVICE_TYPE, domain_name, 'mail')
        except NoServiceIpHelmDatabase:
            return None

    @property
    def source_mail_ipv6(self):
        """Get IPv6 address on which mail service of subscription works on the source panel

        :rtype: str | unicode
        """
        # We consider there is no IPv6 mail addresses in Helm 3
        return None

    def _get_first_real_domain_with_mail(self):
        """Get first real (not fake) domain of subscription with mail"""
        if self.is_fake:
            for site in self.raw_dump.iter_sites():
                if site.mailsystem is not None and site.mailsystem.enabled:
                    return site.name
        else:
            mailsystem = self.raw_dump.mailsystem
            if mailsystem is not None and mailsystem.enabled:
                return self.name

        # None of domains has enabled mailsystem
        return None
