from plesk_mail_migrator.providers.imap.server_detect.methods.base import ImapServerDetectMethod
from plesk_mail_migrator.providers.imap.server_detect.utils import load_mozilla_database, get_first_mx_record, \
    get_parent_domain_chain


class MxRecordWithMozillaDatabaseImapServerDetectMethod(ImapServerDetectMethod):
    """Take the first MX record value and look for IMAP host in Mozilla/Thunderbird database (stored in local file)"""

    def __init__(self, dns_server):
        """
        :param str | unicode dns_server: DNS server IP or hostname
        """
        self._database = load_mozilla_database()
        self._dns_server = dns_server

    def detect(self, domain_name):
        """Detect IMAP host(s) for specified domain name.

        For example, if you have e-mail "john@example.com", and you pass "example.com" to this function,
        it may detect and return two IMAP servers ["imap1.example.com", "imap2.example.com"]

        :type domain_name: str | unicode
        :rtype: list[str | unicode]
        """
        mx_record_value = get_first_mx_record(domain_name, self._dns_server)
        if mx_record_value is not None:
            for checked_domain_name in get_parent_domain_chain(mx_record_value):
                if checked_domain_name in self._database:
                    return self._database[checked_domain_name]

        return []

    def is_fast(self):
        """Whether the method is fast: fast methods do not perform requests to thirdparty services (DNS, HTTP)

        :rtype: bool
        """
        return False

    def get_method_id(self):
        """Get method ID to be used in command line, statistics, etc

        :rtype: str | unicode
        """
        return 'mx-record-with-mozilla-database'
